



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using SubSonic.DataProviders;
using SubSonic.Extensions;
using System.Linq.Expressions;
using SubSonic.Schema;
using System.Collections;
using SubSonic;
using SubSonic.Repository;
using System.ComponentModel;
using System.Data.Common;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Catalyst;
using Catalyst.Xml.Serialization;

namespace RingCast
{

	#region *** ENUM TABLES ***
	
	
	/// <summary>
    /// An enum which represents the ClientStatuses table in the RingCast Database.
    /// </summary>
	public enum ClientStatus
	{
		ENABLED = 1,
		DISABLED = 2,
		PENDING = 3,
		
	}
	
	/// <summary>
    /// An enum which represents the BillingTypes table in the RingCast Database.
    /// </summary>
	public enum BillingType
	{
		INBOUND = 1,
		OUTBOUND = 2,
		NONE = 3,
		
	}
	
	/// <summary>
    /// An enum which represents the MessageDirections table in the RingCast Database.
    /// </summary>
	public enum MessageDirection
	{
		INBOUND = 1,
		OUTBOUND = 2,
		
	}
	
	/// <summary>
    /// An enum which represents the MessageStatuses table in the RingCast Database.
    /// </summary>
	public enum MessageStatus
	{
		SUCCESS = 1,
		FAILURE = 2,
		MESSAGE_RECEIVED = 3,
		MESSAGE_IS_VALID = 4,
		SHORTCODE_HAS_WILDCARD_KEYWORD = 5,
		FOUND_KEYWORD = 6,
		ROUTING_MESSAGE = 7,
		PREPARING_TO_SEND_MESSAGE = 8,
		FOUND_GATEWAY = 9,
		MESSAGE_SENT = 10,
		MULTIPART_PAYMENT = 11,
		MESSAGE_QUEUED = 13,
		MESSAGE_RECEIPT_ERROR = 14,
		MESSAGE_ROUTED_TO_SHELL = 15,
		
	}
	
	/// <summary>
    /// An enum which represents the MessageTypes table in the RingCast Database.
    /// </summary>
	public enum MessageType
	{
		TEXT = 1,
		WAP_PUSH = 2,
		MMS = 3,
		OTA = 4,
		
	}
	
	/// <summary>
    /// An enum which represents the RequestLogTypes table in the RingCast Database.
    /// </summary>
	public enum RequestLogType
	{
		SOAP = 1,
		HTTP_WEB = 2,
		HTTP_WAP = 3,
		
	}

	#endregion
	

	#region *** KEY VALUE TABLES ***
	
	
	/// <summary>
    /// A class which represents the PlatformSettings table in the RingCast Database.
    /// </summary>
	public static class PlatformSettings
	{
		public static string IsOnline
		{
			get { return _PlatformSetting.FetchAll().FirstOrDefault(x => x.Key == "IsOnline").Value; }
		}
		
		public static string Interface_Login
		{
			get { return _PlatformSetting.FetchAll().FirstOrDefault(x => x.Key == "Interface_Login").Value; }
		}
		
		public static string Interface_Password
		{
			get { return _PlatformSetting.FetchAll().FirstOrDefault(x => x.Key == "Interface_Password").Value; }
		}
		
		public static string ApplicationRoot
		{
			get { return _PlatformSetting.FetchAll().FirstOrDefault(x => x.Key == "ApplicationRoot").Value; }
		}
		
		public static string InterfacePath
		{
			get { return _PlatformSetting.FetchAll().FirstOrDefault(x => x.Key == "InterfacePath").Value; }
		}
		
		public static string LogPath
		{
			get { return _PlatformSetting.FetchAll().FirstOrDefault(x => x.Key == "LogPath").Value; }
		}
		
		public static string SMTPServer
		{
			get { return _PlatformSetting.FetchAll().FirstOrDefault(x => x.Key == "SMTPServer").Value; }
		}
		
		public static string InterfaceUrl
		{
			get { return _PlatformSetting.FetchAll().FirstOrDefault(x => x.Key == "InterfaceUrl").Value; }
		}
		
	}

	#endregion
	
 
			
    /// <summary>
    /// A class which represents the aspnet_Users table in the RingCast Database.
    /// </summary>
    public partial class aspnet_User: BusinessObject<aspnet_User>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<aspnet_User>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<aspnet_User> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<aspnet_User>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<aspnet_User> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(aspnet_User item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                aspnet_User item=new aspnet_User();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<aspnet_User> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public aspnet_User(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                aspnet_User.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<aspnet_User>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public aspnet_User(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public aspnet_User(Expression<Func<aspnet_User, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<aspnet_User> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<aspnet_User> _repo;
            
            if(db.TestMode){
                aspnet_User.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<aspnet_User>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<aspnet_User> GetRepo(){
            return GetRepo("","");
        }
        
        public static aspnet_User SingleOrDefault(Expression<Func<aspnet_User, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            aspnet_User single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static aspnet_User SingleOrDefault(Expression<Func<aspnet_User, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            aspnet_User single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<aspnet_User, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<aspnet_User, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<aspnet_User> Find(Expression<Func<aspnet_User, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<aspnet_User> Find(Expression<Func<aspnet_User, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<aspnet_User> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<aspnet_User> All() {
            return GetRepo().GetAll();
        }

		public static List<aspnet_User> FetchAll(string connectionString, string providerName) 
		{
            IRepository<aspnet_User> repo = RingCast.aspnet_User.GetRepo(connectionString,providerName);
			CachedDataLoader<aspnet_User>.DataRequest dataRequest 
			= new CachedDataLoader<aspnet_User>.DataRequest("RingCast", connectionString, "aspnet_Users", repo);

			return CachedDataLoader<aspnet_User>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<aspnet_User> FetchAll(Expression<Func<aspnet_User, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<aspnet_User> repo = RingCast.aspnet_User.GetRepo();
			CachedDataLoader<aspnet_User>.DataRequest dataRequest 
			= new CachedDataLoader<aspnet_User>.DataRequest("RingCast", db.DataProvider.ConnectionString, "aspnet_Users", repo, expression);

			return CachedDataLoader<aspnet_User>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<aspnet_User> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<aspnet_User> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<aspnet_User> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<aspnet_User> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<aspnet_User> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "UserId";
        }

        public object KeyValue()
        {
            return this.UserId;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<Guid>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.UserName.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(aspnet_User)){
                aspnet_User compare=(aspnet_User)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        public string DescriptorValue()
        {
            return this.UserName.ToString();
        }

        public string DescriptorColumn() {
            return "UserName";
        }
        public static string GetKeyColumn()
        {
            return "UserId";
        }        
        public static string GetDescriptorColumn()
        {
            return "UserName";
        }
        
        #region ' Foreign Keys '
		
		private List<ClientUser> _ClientUsers;
		public List<ClientUser> ClientUsers
        {
            get
            {            
				IRepository<ClientUser> repo = RingCast.ClientUser.GetRepo();
				Expression<Func<ClientUser, bool>> expression = x => x.aspnet_UserId == UserId;
				CachedDataLoader<ClientUser>.DataRequest dataRequest 
				= new CachedDataLoader<ClientUser>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "ClientUsers", repo, expression);

				return CachedDataLoader<ClientUser>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _ClientUsers = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        Guid _ApplicationId;
		  
        public Guid ApplicationId
        {
            get { return _ApplicationId; }
            set
            {
                if(_ApplicationId!=value){
                    _ApplicationId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ApplicationId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        Guid _UserId;
		  
        public Guid UserId
        {
            get { return _UserId; }
            set
            {
                if(_UserId!=value){
                    _UserId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="UserId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _UserName;
		  
        public string UserName
        {
            get { return _UserName; }
            set
            {
                if(_UserName!=value){
                    _UserName=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="UserName");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _LoweredUserName;
		  
        public string LoweredUserName
        {
            get { return _LoweredUserName; }
            set
            {
                if(_LoweredUserName!=value){
                    _LoweredUserName=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="LoweredUserName");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _MobileAlias;
		  
        public string MobileAlias
        {
            get { return _MobileAlias; }
            set
            {
                if(_MobileAlias!=value){
                    _MobileAlias=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MobileAlias");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsAnonymous;
		  
        public bool IsAnonymous
        {
            get { return _IsAnonymous; }
            set
            {
                if(_IsAnonymous!=value){
                    _IsAnonymous=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsAnonymous");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _LastActivityDate;
		  
        public DateTime LastActivityDate
        {
            get { return _LastActivityDate; }
            set
            {
                if(_LastActivityDate!=value){
                    _LastActivityDate=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="LastActivityDate");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
        
       
        public void Add(IDataProvider provider){

            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (ClientUsers != null && ClientUsers.Count > 0)
				ClientUsers.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (ClientUsers != null && ClientUsers.Count > 0)
				ClientUsers.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
       
            
            repo.Delete(key);
            
        }
        
        protected void Load(aspnet_User aspnet_User){
			
			if (aspnet_User != null)
			{
				try 
				{
					
					this.ApplicationId = aspnet_User.ApplicationId;
					
										
					this.UserId = aspnet_User.UserId;
					
										
					this.UserName = aspnet_User.UserName;
					
										
					this.LoweredUserName = aspnet_User.LoweredUserName;
					
										
					this.MobileAlias = aspnet_User.MobileAlias;
					
										
					this.IsAnonymous = aspnet_User.IsAnonymous;
					
										
					this.LastActivityDate = aspnet_User.LastActivityDate;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public aspnet_User(aspnet_User aspnet_User):this() {

			Load(aspnet_User);
        }   
        

        public void Delete(IDataProvider provider) {
                   
                 
            _repo.Delete(KeyValue());
            
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<aspnet_User, bool>> expression) {
            var repo = GetRepo();
            
       
            
            return repo.DeleteMany(expression);
            
        }

        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the Pipes table in the RingCast Database.
    /// </summary>
    public partial class Pipe: BusinessObject<Pipe>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<Pipe>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<Pipe> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<Pipe>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<Pipe> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(Pipe item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                Pipe item=new Pipe();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<Pipe> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public Pipe(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                Pipe.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Pipe>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public Pipe(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public Pipe(Expression<Func<Pipe, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<Pipe> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<Pipe> _repo;
            
            if(db.TestMode){
                Pipe.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Pipe>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<Pipe> GetRepo(){
            return GetRepo("","");
        }
        
        public static Pipe SingleOrDefault(Expression<Func<Pipe, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            Pipe single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static Pipe SingleOrDefault(Expression<Func<Pipe, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            Pipe single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<Pipe, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<Pipe, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<Pipe> Find(Expression<Func<Pipe, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<Pipe> Find(Expression<Func<Pipe, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<Pipe> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<Pipe> All() {
            return GetRepo().GetAll();
        }

		public static List<Pipe> FetchAll(string connectionString, string providerName) 
		{
            IRepository<Pipe> repo = RingCast.Pipe.GetRepo(connectionString,providerName);
			CachedDataLoader<Pipe>.DataRequest dataRequest 
			= new CachedDataLoader<Pipe>.DataRequest("RingCast", connectionString, "Pipes", repo);

			return CachedDataLoader<Pipe>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<Pipe> FetchAll(Expression<Func<Pipe, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<Pipe> repo = RingCast.Pipe.GetRepo();
			CachedDataLoader<Pipe>.DataRequest dataRequest 
			= new CachedDataLoader<Pipe>.DataRequest("RingCast", db.DataProvider.ConnectionString, "Pipes", repo, expression);

			return CachedDataLoader<Pipe>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<Pipe> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<Pipe> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<Pipe> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<Pipe> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<Pipe> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Identifier.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(Pipe)){
                Pipe compare=(Pipe)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Identifier.ToString();
        }

        public string DescriptorColumn() {
            return "Identifier";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Identifier";
        }
        
        #region ' Foreign Keys '
		private List<BillingType> _BillingTypes
        {
            get
            {            
				IRepository<_BillingType> repo = RingCast._BillingType.GetRepo();
				Expression<Func<_BillingType, bool>> expression = x => x.Id == BillingTypeId;
				CachedDataLoader<_BillingType>.DataRequest dataRequest 
				= new CachedDataLoader<_BillingType>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "BillingTypes", repo, expression);

				List<BillingType> list = new List<BillingType>();
				
				foreach (_BillingType item in CachedDataLoader<_BillingType>.GetCachedData(dataRequest).ToList())
				{
					list.Add((BillingType)item.Id);
				}
				
				return list;
            }
        }
		
		
		private List<Country> _Countries
        {
            get
            {            
				IRepository<Country> repo = RingCast.Country.GetRepo();
				Expression<Func<Country, bool>> expression = x => x.Id == CountryId;
				CachedDataLoader<Country>.DataRequest dataRequest 
				= new CachedDataLoader<Country>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Countries", repo, expression);

				return CachedDataLoader<Country>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<Gateway> _InboundGateways
        {
            get
            {            
				IRepository<Gateway> repo = RingCast.Gateway.GetRepo();
				Expression<Func<Gateway, bool>> expression = x => x.Id == InboundGatewayId;
				CachedDataLoader<Gateway>.DataRequest dataRequest 
				= new CachedDataLoader<Gateway>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Gateways", repo, expression);

				return CachedDataLoader<Gateway>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<Gateway> _OutboundGateways
        {
            get
            {            
				IRepository<Gateway> repo = RingCast.Gateway.GetRepo();
				Expression<Func<Gateway, bool>> expression = x => x.Id == OutboundGatewayId;
				CachedDataLoader<Gateway>.DataRequest dataRequest 
				= new CachedDataLoader<Gateway>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Gateways", repo, expression);

				return CachedDataLoader<Gateway>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		
		private List<PipeCampaignKeyword> _CampaignKeywords;
		public List<PipeCampaignKeyword> CampaignKeywords
        {
            get
            {            
				IRepository<PipeCampaignKeyword> repo = RingCast.PipeCampaignKeyword.GetRepo();
				Expression<Func<PipeCampaignKeyword, bool>> expression = x => x.PipeId == Id;
				CachedDataLoader<PipeCampaignKeyword>.DataRequest dataRequest 
				= new CachedDataLoader<PipeCampaignKeyword>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "PipeCampaignKeywords", repo, expression);

				return CachedDataLoader<PipeCampaignKeyword>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _CampaignKeywords = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<PipeMapping> _Mappings;
		public List<PipeMapping> Mappings
        {
            get
            {            
				IRepository<PipeMapping> repo = RingCast.PipeMapping.GetRepo();
				Expression<Func<PipeMapping, bool>> expression = x => x.PipeId == Id;
				CachedDataLoader<PipeMapping>.DataRequest dataRequest 
				= new CachedDataLoader<PipeMapping>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "PipeMappings", repo, expression);

				return CachedDataLoader<PipeMapping>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Mappings = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<Message> _Messages;
		public List<Message> Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.PipeId == Id;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Messages = value;
               
               OnChanged();
            }
        }
		
		
		public BillingType BillingType
		{
			get
			{
				return (BillingType)BillingTypeId;
			}								
			set
			{
				BillingTypeId = (int)value;
			}
		}

		public Country Country
		{
			get
			{
				return _Countries.SingleOrDefault(x => x.Id == _CountryId);
			}								
			set
			{
				CountryId = value.Id;
			}
		}

		public Gateway InboundGateway
		{
			get
			{
				return _InboundGateways.SingleOrDefault(x => x.Id == _InboundGatewayId);
			}								
			set
			{
				InboundGatewayId = value.Id;
			}
		}

		public Gateway OutboundGateway
		{
			get
			{
				return _OutboundGateways.SingleOrDefault(x => x.Id == _OutboundGatewayId);
			}								
			set
			{
				OutboundGatewayId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Identifier;
		  
        public string Identifier
        {
            get { return _Identifier; }
            set
            {
                if(_Identifier!=value){
                    _Identifier=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Identifier");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        decimal _Tariff;
		  
        public decimal Tariff
        {
            get { return _Tariff; }
            set
            {
                if(_Tariff!=value){
                    _Tariff=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Tariff");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _InboundGatewayId;
		 [XmlIgnore] 
        public int InboundGatewayId
        {
            get { return _InboundGatewayId; }
            set
            {
                if(_InboundGatewayId!=value){
                    _InboundGatewayId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="InboundGatewayId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _OutboundGatewayId;
		 [XmlIgnore] 
        public int OutboundGatewayId
        {
            get { return _OutboundGatewayId; }
            set
            {
                if(_OutboundGatewayId!=value){
                    _OutboundGatewayId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OutboundGatewayId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _BillingTypeId;
		 [XmlIgnore] 
        public int BillingTypeId
        {
            get { return _BillingTypeId; }
            set
            {
                if(_BillingTypeId!=value){
                    _BillingTypeId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BillingTypeId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _CountryId;
		 [XmlIgnore] 
        public int CountryId
        {
            get { return _CountryId; }
            set
            {
                if(_CountryId!=value){
                    _CountryId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CountryId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsEnabled;
		  
        public bool IsEnabled
        {
            get { return _IsEnabled; }
            set
            {
                if(_IsEnabled!=value){
                    _IsEnabled=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsEnabled");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (CampaignKeywords != null && CampaignKeywords.Count > 0)
				CampaignKeywords.ForEach(x => x.Save(provider));	
				
			
			if (Mappings != null && Mappings.Count > 0)
				Mappings.ForEach(x => x.Save(provider));	
				
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (CampaignKeywords != null && CampaignKeywords.Count > 0)
				CampaignKeywords.ForEach(x => x.Save(username, provider));
				
			
			if (Mappings != null && Mappings.Count > 0)
				Mappings.ForEach(x => x.Save(username, provider));
				
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            Pipe item = new Pipe(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(Pipe pipe){
			
			if (pipe != null)
			{
				try 
				{
					
					this.Id = pipe.Id;
					
										
					this.Identifier = pipe.Identifier;
					
										
					this.Tariff = pipe.Tariff;
					
										
					this.InboundGatewayId = pipe.InboundGatewayId;
					
										
					this.OutboundGatewayId = pipe.OutboundGatewayId;
					
										
					this.BillingTypeId = pipe.BillingTypeId;
					
										
					this.CountryId = pipe.CountryId;
					
										
					this.IsEnabled = pipe.IsEnabled;
					
										
					this.CreatedOn = pipe.CreatedOn;
					
										
					this.CreatedBy = pipe.CreatedBy;
					
										
					this.ModifiedOn = pipe.ModifiedOn;
					
										
					this.ModifiedBy = pipe.ModifiedBy;
					
										
					this.IsDeleted = pipe.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public Pipe(Pipe pipe):this() {

			Load(pipe);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<Pipe, bool>> expression) {
            var repo = GetRepo();
            
            
            List<Pipe> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<Pipe, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the MessageAttachments table in the RingCast Database.
    /// </summary>
    public partial class MessageAttachment: BusinessObject<MessageAttachment>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<MessageAttachment>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<MessageAttachment> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<MessageAttachment>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<MessageAttachment> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(MessageAttachment item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                MessageAttachment item=new MessageAttachment();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<MessageAttachment> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public MessageAttachment(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                MessageAttachment.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<MessageAttachment>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public MessageAttachment(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public MessageAttachment(Expression<Func<MessageAttachment, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<MessageAttachment> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<MessageAttachment> _repo;
            
            if(db.TestMode){
                MessageAttachment.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<MessageAttachment>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<MessageAttachment> GetRepo(){
            return GetRepo("","");
        }
        
        public static MessageAttachment SingleOrDefault(Expression<Func<MessageAttachment, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            MessageAttachment single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static MessageAttachment SingleOrDefault(Expression<Func<MessageAttachment, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            MessageAttachment single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<MessageAttachment, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<MessageAttachment, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<MessageAttachment> Find(Expression<Func<MessageAttachment, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<MessageAttachment> Find(Expression<Func<MessageAttachment, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<MessageAttachment> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<MessageAttachment> All() {
            return GetRepo().GetAll();
        }

		public static List<MessageAttachment> FetchAll(string connectionString, string providerName) 
		{
            IRepository<MessageAttachment> repo = RingCast.MessageAttachment.GetRepo(connectionString,providerName);
			CachedDataLoader<MessageAttachment>.DataRequest dataRequest 
			= new CachedDataLoader<MessageAttachment>.DataRequest("RingCast", connectionString, "MessageAttachments", repo);

			return CachedDataLoader<MessageAttachment>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<MessageAttachment> FetchAll(Expression<Func<MessageAttachment, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<MessageAttachment> repo = RingCast.MessageAttachment.GetRepo();
			CachedDataLoader<MessageAttachment>.DataRequest dataRequest 
			= new CachedDataLoader<MessageAttachment>.DataRequest("RingCast", db.DataProvider.ConnectionString, "MessageAttachments", repo, expression);

			return CachedDataLoader<MessageAttachment>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<MessageAttachment> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<MessageAttachment> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<MessageAttachment> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<MessageAttachment> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<MessageAttachment> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.CreatedBy.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(MessageAttachment)){
                MessageAttachment compare=(MessageAttachment)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.CreatedBy.ToString();
        }

        public string DescriptorColumn() {
            return "CreatedBy";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "CreatedBy";
        }
        
        #region ' Foreign Keys '
		private List<Message> _Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.Id == MessageId;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Message Message
		{
			get
			{
				return _Messages.SingleOrDefault(x => x.Id == _MessageId);
			}								
			set
			{
				MessageId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MessageId;
		 [XmlIgnore] 
        public int MessageId
        {
            get { return _MessageId; }
            set
            {
                if(_MessageId!=value){
                    _MessageId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MessageId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            MessageAttachment item = new MessageAttachment(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(MessageAttachment messageAttachment){
			
			if (messageAttachment != null)
			{
				try 
				{
					
					this.Id = messageAttachment.Id;
					
										
					this.MessageId = messageAttachment.MessageId;
					
										
					this.CreatedOn = messageAttachment.CreatedOn;
					
										
					this.CreatedBy = messageAttachment.CreatedBy;
					
										
					this.ModifiedOn = messageAttachment.ModifiedOn;
					
										
					this.ModifiedBy = messageAttachment.ModifiedBy;
					
										
					this.IsDeleted = messageAttachment.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public MessageAttachment(MessageAttachment messageAttachment):this() {

			Load(messageAttachment);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<MessageAttachment, bool>> expression) {
            var repo = GetRepo();
            
            
            List<MessageAttachment> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<MessageAttachment, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the GatewayCredentials table in the RingCast Database.
    /// </summary>
    public partial class GatewayCredential: BusinessObject<GatewayCredential>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<GatewayCredential>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<GatewayCredential> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<GatewayCredential>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<GatewayCredential> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(GatewayCredential item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                GatewayCredential item=new GatewayCredential();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<GatewayCredential> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public GatewayCredential(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                GatewayCredential.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<GatewayCredential>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public GatewayCredential(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public GatewayCredential(Expression<Func<GatewayCredential, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<GatewayCredential> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<GatewayCredential> _repo;
            
            if(db.TestMode){
                GatewayCredential.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<GatewayCredential>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<GatewayCredential> GetRepo(){
            return GetRepo("","");
        }
        
        public static GatewayCredential SingleOrDefault(Expression<Func<GatewayCredential, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            GatewayCredential single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static GatewayCredential SingleOrDefault(Expression<Func<GatewayCredential, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            GatewayCredential single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<GatewayCredential, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<GatewayCredential, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<GatewayCredential> Find(Expression<Func<GatewayCredential, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<GatewayCredential> Find(Expression<Func<GatewayCredential, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<GatewayCredential> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<GatewayCredential> All() {
            return GetRepo().GetAll();
        }

		public static List<GatewayCredential> FetchAll(string connectionString, string providerName) 
		{
            IRepository<GatewayCredential> repo = RingCast.GatewayCredential.GetRepo(connectionString,providerName);
			CachedDataLoader<GatewayCredential>.DataRequest dataRequest 
			= new CachedDataLoader<GatewayCredential>.DataRequest("RingCast", connectionString, "GatewayCredentials", repo);

			return CachedDataLoader<GatewayCredential>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<GatewayCredential> FetchAll(Expression<Func<GatewayCredential, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<GatewayCredential> repo = RingCast.GatewayCredential.GetRepo();
			CachedDataLoader<GatewayCredential>.DataRequest dataRequest 
			= new CachedDataLoader<GatewayCredential>.DataRequest("RingCast", db.DataProvider.ConnectionString, "GatewayCredentials", repo, expression);

			return CachedDataLoader<GatewayCredential>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<GatewayCredential> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<GatewayCredential> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<GatewayCredential> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<GatewayCredential> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<GatewayCredential> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Key.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(GatewayCredential)){
                GatewayCredential compare=(GatewayCredential)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Key.ToString();
        }

        public string DescriptorColumn() {
            return "Key";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Key";
        }
        
        #region ' Foreign Keys '
		private List<Gateway> _Gateways
        {
            get
            {            
				IRepository<Gateway> repo = RingCast.Gateway.GetRepo();
				Expression<Func<Gateway, bool>> expression = x => x.Id == GatewayId;
				CachedDataLoader<Gateway>.DataRequest dataRequest 
				= new CachedDataLoader<Gateway>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Gateways", repo, expression);

				return CachedDataLoader<Gateway>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		
		private List<ClientGatewayCredential> _ClientGatewayCredentials;
		public List<ClientGatewayCredential> ClientGatewayCredentials
        {
            get
            {            
				IRepository<ClientGatewayCredential> repo = RingCast.ClientGatewayCredential.GetRepo();
				Expression<Func<ClientGatewayCredential, bool>> expression = x => x.GatewayCredentialId == Id;
				CachedDataLoader<ClientGatewayCredential>.DataRequest dataRequest 
				= new CachedDataLoader<ClientGatewayCredential>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "ClientGatewayCredentials", repo, expression);

				return CachedDataLoader<ClientGatewayCredential>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _ClientGatewayCredentials = value;
               
               OnChanged();
            }
        }
		
		
		public Gateway Gateway
		{
			get
			{
				return _Gateways.SingleOrDefault(x => x.Id == _GatewayId);
			}								
			set
			{
				GatewayId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _GatewayId;
		 [XmlIgnore] 
        public int GatewayId
        {
            get { return _GatewayId; }
            set
            {
                if(_GatewayId!=value){
                    _GatewayId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="GatewayId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Key;
		  
        public string Key
        {
            get { return _Key; }
            set
            {
                if(_Key!=value){
                    _Key=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Key");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _DefaultValue;
		  
        public string DefaultValue
        {
            get { return _DefaultValue; }
            set
            {
                if(_DefaultValue!=value){
                    _DefaultValue=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DefaultValue");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (ClientGatewayCredentials != null && ClientGatewayCredentials.Count > 0)
				ClientGatewayCredentials.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (ClientGatewayCredentials != null && ClientGatewayCredentials.Count > 0)
				ClientGatewayCredentials.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            GatewayCredential item = new GatewayCredential(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(GatewayCredential gatewayCredential){
			
			if (gatewayCredential != null)
			{
				try 
				{
					
					this.Id = gatewayCredential.Id;
					
										
					this.GatewayId = gatewayCredential.GatewayId;
					
										
					this.Key = gatewayCredential.Key;
					
										
					this.DefaultValue = gatewayCredential.DefaultValue;
					
										
					this.CreatedOn = gatewayCredential.CreatedOn;
					
										
					this.CreatedBy = gatewayCredential.CreatedBy;
					
										
					this.ModifiedOn = gatewayCredential.ModifiedOn;
					
										
					this.ModifiedBy = gatewayCredential.ModifiedBy;
					
										
					this.IsDeleted = gatewayCredential.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public GatewayCredential(GatewayCredential gatewayCredential):this() {

			Load(gatewayCredential);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<GatewayCredential, bool>> expression) {
            var repo = GetRepo();
            
            
            List<GatewayCredential> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<GatewayCredential, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the ClientGatewayCredentials table in the RingCast Database.
    /// </summary>
    public partial class ClientGatewayCredential: BusinessObject<ClientGatewayCredential>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<ClientGatewayCredential>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<ClientGatewayCredential> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<ClientGatewayCredential>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<ClientGatewayCredential> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(ClientGatewayCredential item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                ClientGatewayCredential item=new ClientGatewayCredential();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<ClientGatewayCredential> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public ClientGatewayCredential(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                ClientGatewayCredential.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<ClientGatewayCredential>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public ClientGatewayCredential(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public ClientGatewayCredential(Expression<Func<ClientGatewayCredential, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<ClientGatewayCredential> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<ClientGatewayCredential> _repo;
            
            if(db.TestMode){
                ClientGatewayCredential.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<ClientGatewayCredential>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<ClientGatewayCredential> GetRepo(){
            return GetRepo("","");
        }
        
        public static ClientGatewayCredential SingleOrDefault(Expression<Func<ClientGatewayCredential, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            ClientGatewayCredential single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static ClientGatewayCredential SingleOrDefault(Expression<Func<ClientGatewayCredential, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            ClientGatewayCredential single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<ClientGatewayCredential, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<ClientGatewayCredential, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<ClientGatewayCredential> Find(Expression<Func<ClientGatewayCredential, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<ClientGatewayCredential> Find(Expression<Func<ClientGatewayCredential, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<ClientGatewayCredential> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<ClientGatewayCredential> All() {
            return GetRepo().GetAll();
        }

		public static List<ClientGatewayCredential> FetchAll(string connectionString, string providerName) 
		{
            IRepository<ClientGatewayCredential> repo = RingCast.ClientGatewayCredential.GetRepo(connectionString,providerName);
			CachedDataLoader<ClientGatewayCredential>.DataRequest dataRequest 
			= new CachedDataLoader<ClientGatewayCredential>.DataRequest("RingCast", connectionString, "ClientGatewayCredentials", repo);

			return CachedDataLoader<ClientGatewayCredential>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<ClientGatewayCredential> FetchAll(Expression<Func<ClientGatewayCredential, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<ClientGatewayCredential> repo = RingCast.ClientGatewayCredential.GetRepo();
			CachedDataLoader<ClientGatewayCredential>.DataRequest dataRequest 
			= new CachedDataLoader<ClientGatewayCredential>.DataRequest("RingCast", db.DataProvider.ConnectionString, "ClientGatewayCredentials", repo, expression);

			return CachedDataLoader<ClientGatewayCredential>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<ClientGatewayCredential> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<ClientGatewayCredential> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<ClientGatewayCredential> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<ClientGatewayCredential> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<ClientGatewayCredential> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Value.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(ClientGatewayCredential)){
                ClientGatewayCredential compare=(ClientGatewayCredential)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Value.ToString();
        }

        public string DescriptorColumn() {
            return "Value";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Value";
        }
        
        #region ' Foreign Keys '
		private List<Client> _Clients
        {
            get
            {            
				IRepository<Client> repo = RingCast.Client.GetRepo();
				Expression<Func<Client, bool>> expression = x => x.Id == ClientId;
				CachedDataLoader<Client>.DataRequest dataRequest 
				= new CachedDataLoader<Client>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Clients", repo, expression);

				return CachedDataLoader<Client>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<GatewayCredential> _GatewayCredentials
        {
            get
            {            
				IRepository<GatewayCredential> repo = RingCast.GatewayCredential.GetRepo();
				Expression<Func<GatewayCredential, bool>> expression = x => x.Id == GatewayCredentialId;
				CachedDataLoader<GatewayCredential>.DataRequest dataRequest 
				= new CachedDataLoader<GatewayCredential>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "GatewayCredentials", repo, expression);

				return CachedDataLoader<GatewayCredential>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Client Client
		{
			get
			{
				return _Clients.SingleOrDefault(x => x.Id == _ClientId);
			}								
			set
			{
				ClientId = value.Id;
			}
		}

		public GatewayCredential GatewayCredential
		{
			get
			{
				return _GatewayCredentials.SingleOrDefault(x => x.Id == _GatewayCredentialId);
			}								
			set
			{
				GatewayCredentialId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _ClientId;
		 [XmlIgnore] 
        public int ClientId
        {
            get { return _ClientId; }
            set
            {
                if(_ClientId!=value){
                    _ClientId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ClientId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _GatewayCredentialId;
		 [XmlIgnore] 
        public int GatewayCredentialId
        {
            get { return _GatewayCredentialId; }
            set
            {
                if(_GatewayCredentialId!=value){
                    _GatewayCredentialId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="GatewayCredentialId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Value;
		  
        public string Value
        {
            get { return _Value; }
            set
            {
                if(_Value!=value){
                    _Value=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Value");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            ClientGatewayCredential item = new ClientGatewayCredential(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(ClientGatewayCredential clientGatewayCredential){
			
			if (clientGatewayCredential != null)
			{
				try 
				{
					
					this.Id = clientGatewayCredential.Id;
					
										
					this.ClientId = clientGatewayCredential.ClientId;
					
										
					this.GatewayCredentialId = clientGatewayCredential.GatewayCredentialId;
					
										
					this.Value = clientGatewayCredential.Value;
					
										
					this.CreatedOn = clientGatewayCredential.CreatedOn;
					
										
					this.CreatedBy = clientGatewayCredential.CreatedBy;
					
										
					this.ModifiedOn = clientGatewayCredential.ModifiedOn;
					
										
					this.ModifiedBy = clientGatewayCredential.ModifiedBy;
					
										
					this.IsDeleted = clientGatewayCredential.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public ClientGatewayCredential(ClientGatewayCredential clientGatewayCredential):this() {

			Load(clientGatewayCredential);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<ClientGatewayCredential, bool>> expression) {
            var repo = GetRepo();
            
            
            List<ClientGatewayCredential> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<ClientGatewayCredential, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the RequestLogTypes table in the RingCast Database.
    /// </summary>
    public partial class _RequestLogType: BusinessObject<_RequestLogType>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<_RequestLogType>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<_RequestLogType> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<_RequestLogType>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<_RequestLogType> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(_RequestLogType item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                _RequestLogType item=new _RequestLogType();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<_RequestLogType> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public _RequestLogType(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                _RequestLogType.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_RequestLogType>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public _RequestLogType(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public _RequestLogType(Expression<Func<_RequestLogType, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<_RequestLogType> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<_RequestLogType> _repo;
            
            if(db.TestMode){
                _RequestLogType.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_RequestLogType>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<_RequestLogType> GetRepo(){
            return GetRepo("","");
        }
        
        public static _RequestLogType SingleOrDefault(Expression<Func<_RequestLogType, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            _RequestLogType single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static _RequestLogType SingleOrDefault(Expression<Func<_RequestLogType, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            _RequestLogType single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<_RequestLogType, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<_RequestLogType, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<_RequestLogType> Find(Expression<Func<_RequestLogType, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<_RequestLogType> Find(Expression<Func<_RequestLogType, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<_RequestLogType> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<_RequestLogType> All() {
            return GetRepo().GetAll();
        }

		public static List<_RequestLogType> FetchAll(string connectionString, string providerName) 
		{
            IRepository<_RequestLogType> repo = RingCast._RequestLogType.GetRepo(connectionString,providerName);
			CachedDataLoader<_RequestLogType>.DataRequest dataRequest 
			= new CachedDataLoader<_RequestLogType>.DataRequest("RingCast", connectionString, "RequestLogTypes", repo);

			return CachedDataLoader<_RequestLogType>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<_RequestLogType> FetchAll(Expression<Func<_RequestLogType, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<_RequestLogType> repo = RingCast._RequestLogType.GetRepo();
			CachedDataLoader<_RequestLogType>.DataRequest dataRequest 
			= new CachedDataLoader<_RequestLogType>.DataRequest("RingCast", db.DataProvider.ConnectionString, "RequestLogTypes", repo, expression);

			return CachedDataLoader<_RequestLogType>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<_RequestLogType> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<_RequestLogType> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<_RequestLogType> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<_RequestLogType> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<_RequestLogType> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(_RequestLogType)){
                _RequestLogType compare=(_RequestLogType)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<RequestLog> _RequestLogs;
		public List<RequestLog> RequestLogs
        {
            get
            {            
				IRepository<RequestLog> repo = RingCast.RequestLog.GetRepo();
				Expression<Func<RequestLog, bool>> expression = x => x.RequestLogTypeId == Id;
				CachedDataLoader<RequestLog>.DataRequest dataRequest 
				= new CachedDataLoader<RequestLog>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "RequestLog", repo, expression);

				return CachedDataLoader<RequestLog>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _RequestLogs = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (RequestLogs != null && RequestLogs.Count > 0)
				RequestLogs.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (RequestLogs != null && RequestLogs.Count > 0)
				RequestLogs.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            _RequestLogType item = new _RequestLogType(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(_RequestLogType _RequestLogType){
			
			if (_RequestLogType != null)
			{
				try 
				{
					
					this.Id = _RequestLogType.Id;
					
										
					this.Name = _RequestLogType.Name;
					
										
					this.CreatedOn = _RequestLogType.CreatedOn;
					
										
					this.CreatedBy = _RequestLogType.CreatedBy;
					
										
					this.ModifiedOn = _RequestLogType.ModifiedOn;
					
										
					this.ModifiedBy = _RequestLogType.ModifiedBy;
					
										
					this.IsDeleted = _RequestLogType.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public _RequestLogType(_RequestLogType _RequestLogType):this() {

			Load(_RequestLogType);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<_RequestLogType, bool>> expression) {
            var repo = GetRepo();
            
            
            List<_RequestLogType> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<_RequestLogType, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the RequestLog table in the RingCast Database.
    /// </summary>
    public partial class RequestLog: BusinessObject<RequestLog>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<RequestLog>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<RequestLog> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<RequestLog>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<RequestLog> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(RequestLog item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                RequestLog item=new RequestLog();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<RequestLog> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public RequestLog(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                RequestLog.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<RequestLog>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public RequestLog(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public RequestLog(Expression<Func<RequestLog, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<RequestLog> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<RequestLog> _repo;
            
            if(db.TestMode){
                RequestLog.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<RequestLog>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<RequestLog> GetRepo(){
            return GetRepo("","");
        }
        
        public static RequestLog SingleOrDefault(Expression<Func<RequestLog, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            RequestLog single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static RequestLog SingleOrDefault(Expression<Func<RequestLog, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            RequestLog single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<RequestLog, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<RequestLog, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<RequestLog> Find(Expression<Func<RequestLog, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<RequestLog> Find(Expression<Func<RequestLog, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<RequestLog> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<RequestLog> All() {
            return GetRepo().GetAll();
        }

		public static List<RequestLog> FetchAll(string connectionString, string providerName) 
		{
            IRepository<RequestLog> repo = RingCast.RequestLog.GetRepo(connectionString,providerName);
			CachedDataLoader<RequestLog>.DataRequest dataRequest 
			= new CachedDataLoader<RequestLog>.DataRequest("RingCast", connectionString, "RequestLog", repo);

			return CachedDataLoader<RequestLog>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<RequestLog> FetchAll(Expression<Func<RequestLog, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<RequestLog> repo = RingCast.RequestLog.GetRepo();
			CachedDataLoader<RequestLog>.DataRequest dataRequest 
			= new CachedDataLoader<RequestLog>.DataRequest("RingCast", db.DataProvider.ConnectionString, "RequestLog", repo, expression);

			return CachedDataLoader<RequestLog>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<RequestLog> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<RequestLog> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<RequestLog> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<RequestLog> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<RequestLog> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.URL.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(RequestLog)){
                RequestLog compare=(RequestLog)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.URL.ToString();
        }

        public string DescriptorColumn() {
            return "URL";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "URL";
        }
        
        #region ' Foreign Keys '
		private List<RequestLogType> _RequestLogTypes
        {
            get
            {            
				IRepository<_RequestLogType> repo = RingCast._RequestLogType.GetRepo();
				Expression<Func<_RequestLogType, bool>> expression = x => x.Id == RequestLogTypeId;
				CachedDataLoader<_RequestLogType>.DataRequest dataRequest 
				= new CachedDataLoader<_RequestLogType>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "RequestLogTypes", repo, expression);

				List<RequestLogType> list = new List<RequestLogType>();
				
				foreach (_RequestLogType item in CachedDataLoader<_RequestLogType>.GetCachedData(dataRequest).ToList())
				{
					list.Add((RequestLogType)item.Id);
				}
				
				return list;
            }
        }
		
		
		
		private List<Message> _Messages;
		public List<Message> Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.RequestLogId == Id;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Messages = value;
               
               OnChanged();
            }
        }
		
		
		public RequestLogType Type
		{
			get
			{
				return (RequestLogType)RequestLogTypeId;
			}								
			set
			{
				RequestLogTypeId = (int)value;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _URL;
		  
        public string URL
        {
            get { return _URL; }
            set
            {
                if(_URL!=value){
                    _URL=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="URL");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Request;
		  
        public string Request
        {
            get { return _Request; }
            set
            {
                if(_Request!=value){
                    _Request=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Request");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _IP;
		  
        public string IP
        {
            get { return _IP; }
            set
            {
                if(_IP!=value){
                    _IP=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IP");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _CountryId;
		  
        public int CountryId
        {
            get { return _CountryId; }
            set
            {
                if(_CountryId!=value){
                    _CountryId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CountryId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _RequestLogTypeId;
		  
        public int RequestLogTypeId
        {
            get { return _RequestLogTypeId; }
            set
            {
                if(_RequestLogTypeId!=value){
                    _RequestLogTypeId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="RequestLogTypeId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            RequestLog item = new RequestLog(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(RequestLog requestLog){
			
			if (requestLog != null)
			{
				try 
				{
					
					this.Id = requestLog.Id;
					
										
					this.URL = requestLog.URL;
					
										
					this.Request = requestLog.Request;
					
										
					this.IP = requestLog.IP;
					
										
					this.CountryId = requestLog.CountryId;
					
										
					this.RequestLogTypeId = requestLog.RequestLogTypeId;
					
										
					this.CreatedOn = requestLog.CreatedOn;
					
										
					this.CreatedBy = requestLog.CreatedBy;
					
										
					this.ModifiedOn = requestLog.ModifiedOn;
					
										
					this.ModifiedBy = requestLog.ModifiedBy;
					
										
					this.IsDeleted = requestLog.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public RequestLog(RequestLog requestLog):this() {

			Load(requestLog);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<RequestLog, bool>> expression) {
            var repo = GetRepo();
            
            
            List<RequestLog> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<RequestLog, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the Sessions table in the RingCast Database.
    /// </summary>
    public partial class Session: BusinessObject<Session>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<Session>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<Session> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<Session>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<Session> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(Session item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                Session item=new Session();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<Session> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public Session(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                Session.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Session>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public Session(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public Session(Expression<Func<Session, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<Session> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<Session> _repo;
            
            if(db.TestMode){
                Session.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Session>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<Session> GetRepo(){
            return GetRepo("","");
        }
        
        public static Session SingleOrDefault(Expression<Func<Session, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            Session single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static Session SingleOrDefault(Expression<Func<Session, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            Session single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<Session, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<Session, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<Session> Find(Expression<Func<Session, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<Session> Find(Expression<Func<Session, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<Session> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<Session> All() {
            return GetRepo().GetAll();
        }

		public static List<Session> FetchAll(string connectionString, string providerName) 
		{
            IRepository<Session> repo = RingCast.Session.GetRepo(connectionString,providerName);
			CachedDataLoader<Session>.DataRequest dataRequest 
			= new CachedDataLoader<Session>.DataRequest("RingCast", connectionString, "Sessions", repo);

			return CachedDataLoader<Session>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<Session> FetchAll(Expression<Func<Session, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<Session> repo = RingCast.Session.GetRepo();
			CachedDataLoader<Session>.DataRequest dataRequest 
			= new CachedDataLoader<Session>.DataRequest("RingCast", db.DataProvider.ConnectionString, "Sessions", repo, expression);

			return CachedDataLoader<Session>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<Session> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<Session> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<Session> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<Session> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<Session> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.CreatedBy.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(Session)){
                Session compare=(Session)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.CreatedBy.ToString();
        }

        public string DescriptorColumn() {
            return "CreatedBy";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "CreatedBy";
        }
        
        #region ' Foreign Keys '
		private List<Campaign> _Campaigns
        {
            get
            {            
				IRepository<Campaign> repo = RingCast.Campaign.GetRepo();
				Expression<Func<Campaign, bool>> expression = x => x.Id == CampaignId;
				CachedDataLoader<Campaign>.DataRequest dataRequest 
				= new CachedDataLoader<Campaign>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Campaigns", repo, expression);

				return CachedDataLoader<Campaign>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		
		private List<Message> _Messages;
		public List<Message> Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.SessionId == Id;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Messages = value;
               
               OnChanged();
            }
        }
		
		
		public Campaign Campaign
		{
			get
			{
				return _Campaigns.SingleOrDefault(x => x.Id == _CampaignId);
			}								
			set
			{
				CampaignId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _CampaignId;
		 [XmlIgnore] 
        public int CampaignId
        {
            get { return _CampaignId; }
            set
            {
                if(_CampaignId!=value){
                    _CampaignId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CampaignId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsClosed;
		  
        public bool IsClosed
        {
            get { return _IsClosed; }
            set
            {
                if(_IsClosed!=value){
                    _IsClosed=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsClosed");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            Session item = new Session(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(Session session){
			
			if (session != null)
			{
				try 
				{
					
					this.Id = session.Id;
					
										
					this.CampaignId = session.CampaignId;
					
										
					this.IsClosed = session.IsClosed;
					
										
					this.CreatedOn = session.CreatedOn;
					
										
					this.CreatedBy = session.CreatedBy;
					
										
					this.ModifiedOn = session.ModifiedOn;
					
										
					this.ModifiedBy = session.ModifiedBy;
					
										
					this.IsDeleted = session.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public Session(Session session):this() {

			Load(session);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<Session, bool>> expression) {
            var repo = GetRepo();
            
            
            List<Session> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<Session, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the PlatformSettings table in the RingCast Database.
    /// </summary>
    public partial class _PlatformSetting: BusinessObject<_PlatformSetting>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<_PlatformSetting>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<_PlatformSetting> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<_PlatformSetting>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<_PlatformSetting> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(_PlatformSetting item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                _PlatformSetting item=new _PlatformSetting();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<_PlatformSetting> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public _PlatformSetting(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                _PlatformSetting.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_PlatformSetting>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public _PlatformSetting(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public _PlatformSetting(Expression<Func<_PlatformSetting, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<_PlatformSetting> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<_PlatformSetting> _repo;
            
            if(db.TestMode){
                _PlatformSetting.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_PlatformSetting>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<_PlatformSetting> GetRepo(){
            return GetRepo("","");
        }
        
        public static _PlatformSetting SingleOrDefault(Expression<Func<_PlatformSetting, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            _PlatformSetting single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static _PlatformSetting SingleOrDefault(Expression<Func<_PlatformSetting, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            _PlatformSetting single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<_PlatformSetting, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<_PlatformSetting, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<_PlatformSetting> Find(Expression<Func<_PlatformSetting, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<_PlatformSetting> Find(Expression<Func<_PlatformSetting, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<_PlatformSetting> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<_PlatformSetting> All() {
            return GetRepo().GetAll();
        }

		public static List<_PlatformSetting> FetchAll(string connectionString, string providerName) 
		{
            IRepository<_PlatformSetting> repo = RingCast._PlatformSetting.GetRepo(connectionString,providerName);
			CachedDataLoader<_PlatformSetting>.DataRequest dataRequest 
			= new CachedDataLoader<_PlatformSetting>.DataRequest("RingCast", connectionString, "PlatformSettings", repo);

			return CachedDataLoader<_PlatformSetting>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<_PlatformSetting> FetchAll(Expression<Func<_PlatformSetting, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<_PlatformSetting> repo = RingCast._PlatformSetting.GetRepo();
			CachedDataLoader<_PlatformSetting>.DataRequest dataRequest 
			= new CachedDataLoader<_PlatformSetting>.DataRequest("RingCast", db.DataProvider.ConnectionString, "PlatformSettings", repo, expression);

			return CachedDataLoader<_PlatformSetting>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<_PlatformSetting> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<_PlatformSetting> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<_PlatformSetting> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<_PlatformSetting> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<_PlatformSetting> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Key.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(_PlatformSetting)){
                _PlatformSetting compare=(_PlatformSetting)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Key.ToString();
        }

        public string DescriptorColumn() {
            return "Key";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Key";
        }
        
        #region ' Foreign Keys '
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Key;
		  
        public string Key
        {
            get { return _Key; }
            set
            {
                if(_Key!=value){
                    _Key=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Key");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Value;
		  
        public string Value
        {
            get { return _Value; }
            set
            {
                if(_Value!=value){
                    _Value=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Value");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            _PlatformSetting item = new _PlatformSetting(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(_PlatformSetting _PlatformSetting){
			
			if (_PlatformSetting != null)
			{
				try 
				{
					
					this.Id = _PlatformSetting.Id;
					
										
					this.Key = _PlatformSetting.Key;
					
										
					this.Value = _PlatformSetting.Value;
					
										
					this.CreatedOn = _PlatformSetting.CreatedOn;
					
										
					this.CreatedBy = _PlatformSetting.CreatedBy;
					
										
					this.ModifiedOn = _PlatformSetting.ModifiedOn;
					
										
					this.ModifiedBy = _PlatformSetting.ModifiedBy;
					
										
					this.IsDeleted = _PlatformSetting.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public _PlatformSetting(_PlatformSetting _PlatformSetting):this() {

			Load(_PlatformSetting);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<_PlatformSetting, bool>> expression) {
            var repo = GetRepo();
            
            
            List<_PlatformSetting> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<_PlatformSetting, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the GatewayIPs table in the RingCast Database.
    /// </summary>
    public partial class GatewayIP: BusinessObject<GatewayIP>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<GatewayIP>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<GatewayIP> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<GatewayIP>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<GatewayIP> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(GatewayIP item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                GatewayIP item=new GatewayIP();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<GatewayIP> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public GatewayIP(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                GatewayIP.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<GatewayIP>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public GatewayIP(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public GatewayIP(Expression<Func<GatewayIP, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<GatewayIP> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<GatewayIP> _repo;
            
            if(db.TestMode){
                GatewayIP.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<GatewayIP>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<GatewayIP> GetRepo(){
            return GetRepo("","");
        }
        
        public static GatewayIP SingleOrDefault(Expression<Func<GatewayIP, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            GatewayIP single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static GatewayIP SingleOrDefault(Expression<Func<GatewayIP, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            GatewayIP single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<GatewayIP, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<GatewayIP, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<GatewayIP> Find(Expression<Func<GatewayIP, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<GatewayIP> Find(Expression<Func<GatewayIP, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<GatewayIP> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<GatewayIP> All() {
            return GetRepo().GetAll();
        }

		public static List<GatewayIP> FetchAll(string connectionString, string providerName) 
		{
            IRepository<GatewayIP> repo = RingCast.GatewayIP.GetRepo(connectionString,providerName);
			CachedDataLoader<GatewayIP>.DataRequest dataRequest 
			= new CachedDataLoader<GatewayIP>.DataRequest("RingCast", connectionString, "GatewayIPs", repo);

			return CachedDataLoader<GatewayIP>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<GatewayIP> FetchAll(Expression<Func<GatewayIP, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<GatewayIP> repo = RingCast.GatewayIP.GetRepo();
			CachedDataLoader<GatewayIP>.DataRequest dataRequest 
			= new CachedDataLoader<GatewayIP>.DataRequest("RingCast", db.DataProvider.ConnectionString, "GatewayIPs", repo, expression);

			return CachedDataLoader<GatewayIP>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<GatewayIP> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<GatewayIP> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<GatewayIP> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<GatewayIP> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<GatewayIP> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.IPAddress.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(GatewayIP)){
                GatewayIP compare=(GatewayIP)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.IPAddress.ToString();
        }

        public string DescriptorColumn() {
            return "IPAddress";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "IPAddress";
        }
        
        #region ' Foreign Keys '
		private List<Gateway> _Gateways
        {
            get
            {            
				IRepository<Gateway> repo = RingCast.Gateway.GetRepo();
				Expression<Func<Gateway, bool>> expression = x => x.Id == GatewayId;
				CachedDataLoader<Gateway>.DataRequest dataRequest 
				= new CachedDataLoader<Gateway>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Gateways", repo, expression);

				return CachedDataLoader<Gateway>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Gateway Gateway
		{
			get
			{
				return _Gateways.SingleOrDefault(x => x.Id == _GatewayId);
			}								
			set
			{
				GatewayId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _GatewayId;
		 [XmlIgnore] 
        public int GatewayId
        {
            get { return _GatewayId; }
            set
            {
                if(_GatewayId!=value){
                    _GatewayId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="GatewayId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _IPAddress;
		  
        public string IPAddress
        {
            get { return _IPAddress; }
            set
            {
                if(_IPAddress!=value){
                    _IPAddress=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IPAddress");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            GatewayIP item = new GatewayIP(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(GatewayIP gatewayIP){
			
			if (gatewayIP != null)
			{
				try 
				{
					
					this.Id = gatewayIP.Id;
					
										
					this.GatewayId = gatewayIP.GatewayId;
					
										
					this.IPAddress = gatewayIP.IPAddress;
					
										
					this.CreatedOn = gatewayIP.CreatedOn;
					
										
					this.CreatedBy = gatewayIP.CreatedBy;
					
										
					this.ModifiedOn = gatewayIP.ModifiedOn;
					
										
					this.ModifiedBy = gatewayIP.ModifiedBy;
					
										
					this.IsDeleted = gatewayIP.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public GatewayIP(GatewayIP gatewayIP):this() {

			Load(gatewayIP);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<GatewayIP, bool>> expression) {
            var repo = GetRepo();
            
            
            List<GatewayIP> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<GatewayIP, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the Shells table in the RingCast Database.
    /// </summary>
    public partial class Shell: BusinessObject<Shell>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<Shell>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<Shell> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<Shell>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<Shell> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(Shell item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                Shell item=new Shell();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<Shell> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public Shell(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                Shell.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Shell>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public Shell(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public Shell(Expression<Func<Shell, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<Shell> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<Shell> _repo;
            
            if(db.TestMode){
                Shell.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Shell>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<Shell> GetRepo(){
            return GetRepo("","");
        }
        
        public static Shell SingleOrDefault(Expression<Func<Shell, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            Shell single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static Shell SingleOrDefault(Expression<Func<Shell, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            Shell single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<Shell, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<Shell, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<Shell> Find(Expression<Func<Shell, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<Shell> Find(Expression<Func<Shell, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<Shell> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<Shell> All() {
            return GetRepo().GetAll();
        }

		public static List<Shell> FetchAll(string connectionString, string providerName) 
		{
            IRepository<Shell> repo = RingCast.Shell.GetRepo(connectionString,providerName);
			CachedDataLoader<Shell>.DataRequest dataRequest 
			= new CachedDataLoader<Shell>.DataRequest("RingCast", connectionString, "Shells", repo);

			return CachedDataLoader<Shell>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<Shell> FetchAll(Expression<Func<Shell, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<Shell> repo = RingCast.Shell.GetRepo();
			CachedDataLoader<Shell>.DataRequest dataRequest 
			= new CachedDataLoader<Shell>.DataRequest("RingCast", db.DataProvider.ConnectionString, "Shells", repo, expression);

			return CachedDataLoader<Shell>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<Shell> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<Shell> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<Shell> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<Shell> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<Shell> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(Shell)){
                Shell compare=(Shell)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<CampaignShell> _CampaignShells;
		public List<CampaignShell> CampaignShells
        {
            get
            {            
				IRepository<CampaignShell> repo = RingCast.CampaignShell.GetRepo();
				Expression<Func<CampaignShell, bool>> expression = x => x.ShellId == Id;
				CachedDataLoader<CampaignShell>.DataRequest dataRequest 
				= new CachedDataLoader<CampaignShell>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "CampaignShells", repo, expression);

				return CachedDataLoader<CampaignShell>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _CampaignShells = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<ShellCredential> _Credentials;
		public List<ShellCredential> Credentials
        {
            get
            {            
				IRepository<ShellCredential> repo = RingCast.ShellCredential.GetRepo();
				Expression<Func<ShellCredential, bool>> expression = x => x.ShellId == Id;
				CachedDataLoader<ShellCredential>.DataRequest dataRequest 
				= new CachedDataLoader<ShellCredential>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "ShellCredentials", repo, expression);

				return CachedDataLoader<ShellCredential>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Credentials = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ProviderName;
		  
        public string ProviderName
        {
            get { return _ProviderName; }
            set
            {
                if(_ProviderName!=value){
                    _ProviderName=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ProviderName");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ProviderType;
		  
        public string ProviderType
        {
            get { return _ProviderType; }
            set
            {
                if(_ProviderType!=value){
                    _ProviderType=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ProviderType");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsEnabled;
		  
        public bool IsEnabled
        {
            get { return _IsEnabled; }
            set
            {
                if(_IsEnabled!=value){
                    _IsEnabled=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsEnabled");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (CampaignShells != null && CampaignShells.Count > 0)
				CampaignShells.ForEach(x => x.Save(provider));	
				
			
			if (Credentials != null && Credentials.Count > 0)
				Credentials.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (CampaignShells != null && CampaignShells.Count > 0)
				CampaignShells.ForEach(x => x.Save(username, provider));
				
			
			if (Credentials != null && Credentials.Count > 0)
				Credentials.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            Shell item = new Shell(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(Shell shell){
			
			if (shell != null)
			{
				try 
				{
					
					this.Id = shell.Id;
					
										
					this.Name = shell.Name;
					
										
					this.ProviderName = shell.ProviderName;
					
										
					this.ProviderType = shell.ProviderType;
					
										
					this.IsEnabled = shell.IsEnabled;
					
										
					this.CreatedOn = shell.CreatedOn;
					
										
					this.CreatedBy = shell.CreatedBy;
					
										
					this.ModifiedOn = shell.ModifiedOn;
					
										
					this.ModifiedBy = shell.ModifiedBy;
					
										
					this.IsDeleted = shell.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public Shell(Shell shell):this() {

			Load(shell);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<Shell, bool>> expression) {
            var repo = GetRepo();
            
            
            List<Shell> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<Shell, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the MessageTypes table in the RingCast Database.
    /// </summary>
    public partial class _MessageType: BusinessObject<_MessageType>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<_MessageType>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<_MessageType> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<_MessageType>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<_MessageType> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(_MessageType item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                _MessageType item=new _MessageType();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<_MessageType> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public _MessageType(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                _MessageType.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_MessageType>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public _MessageType(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public _MessageType(Expression<Func<_MessageType, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<_MessageType> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<_MessageType> _repo;
            
            if(db.TestMode){
                _MessageType.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_MessageType>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<_MessageType> GetRepo(){
            return GetRepo("","");
        }
        
        public static _MessageType SingleOrDefault(Expression<Func<_MessageType, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            _MessageType single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static _MessageType SingleOrDefault(Expression<Func<_MessageType, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            _MessageType single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<_MessageType, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<_MessageType, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<_MessageType> Find(Expression<Func<_MessageType, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<_MessageType> Find(Expression<Func<_MessageType, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<_MessageType> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<_MessageType> All() {
            return GetRepo().GetAll();
        }

		public static List<_MessageType> FetchAll(string connectionString, string providerName) 
		{
            IRepository<_MessageType> repo = RingCast._MessageType.GetRepo(connectionString,providerName);
			CachedDataLoader<_MessageType>.DataRequest dataRequest 
			= new CachedDataLoader<_MessageType>.DataRequest("RingCast", connectionString, "MessageTypes", repo);

			return CachedDataLoader<_MessageType>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<_MessageType> FetchAll(Expression<Func<_MessageType, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<_MessageType> repo = RingCast._MessageType.GetRepo();
			CachedDataLoader<_MessageType>.DataRequest dataRequest 
			= new CachedDataLoader<_MessageType>.DataRequest("RingCast", db.DataProvider.ConnectionString, "MessageTypes", repo, expression);

			return CachedDataLoader<_MessageType>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<_MessageType> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<_MessageType> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<_MessageType> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<_MessageType> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<_MessageType> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(_MessageType)){
                _MessageType compare=(_MessageType)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<Message> _Messages;
		public List<Message> Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.MessageTypeId == Id;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Messages = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            _MessageType item = new _MessageType(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(_MessageType _MessageType){
			
			if (_MessageType != null)
			{
				try 
				{
					
					this.Id = _MessageType.Id;
					
										
					this.Name = _MessageType.Name;
					
										
					this.CreatedOn = _MessageType.CreatedOn;
					
										
					this.CreatedBy = _MessageType.CreatedBy;
					
										
					this.ModifiedOn = _MessageType.ModifiedOn;
					
										
					this.ModifiedBy = _MessageType.ModifiedBy;
					
										
					this.IsDeleted = _MessageType.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public _MessageType(_MessageType _MessageType):this() {

			Load(_MessageType);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<_MessageType, bool>> expression) {
            var repo = GetRepo();
            
            
            List<_MessageType> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<_MessageType, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the ShellCredentials table in the RingCast Database.
    /// </summary>
    public partial class ShellCredential: BusinessObject<ShellCredential>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<ShellCredential>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<ShellCredential> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<ShellCredential>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<ShellCredential> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(ShellCredential item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                ShellCredential item=new ShellCredential();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<ShellCredential> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public ShellCredential(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                ShellCredential.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<ShellCredential>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public ShellCredential(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public ShellCredential(Expression<Func<ShellCredential, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<ShellCredential> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<ShellCredential> _repo;
            
            if(db.TestMode){
                ShellCredential.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<ShellCredential>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<ShellCredential> GetRepo(){
            return GetRepo("","");
        }
        
        public static ShellCredential SingleOrDefault(Expression<Func<ShellCredential, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            ShellCredential single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static ShellCredential SingleOrDefault(Expression<Func<ShellCredential, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            ShellCredential single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<ShellCredential, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<ShellCredential, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<ShellCredential> Find(Expression<Func<ShellCredential, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<ShellCredential> Find(Expression<Func<ShellCredential, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<ShellCredential> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<ShellCredential> All() {
            return GetRepo().GetAll();
        }

		public static List<ShellCredential> FetchAll(string connectionString, string providerName) 
		{
            IRepository<ShellCredential> repo = RingCast.ShellCredential.GetRepo(connectionString,providerName);
			CachedDataLoader<ShellCredential>.DataRequest dataRequest 
			= new CachedDataLoader<ShellCredential>.DataRequest("RingCast", connectionString, "ShellCredentials", repo);

			return CachedDataLoader<ShellCredential>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<ShellCredential> FetchAll(Expression<Func<ShellCredential, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<ShellCredential> repo = RingCast.ShellCredential.GetRepo();
			CachedDataLoader<ShellCredential>.DataRequest dataRequest 
			= new CachedDataLoader<ShellCredential>.DataRequest("RingCast", db.DataProvider.ConnectionString, "ShellCredentials", repo, expression);

			return CachedDataLoader<ShellCredential>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<ShellCredential> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<ShellCredential> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<ShellCredential> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<ShellCredential> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<ShellCredential> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Key.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(ShellCredential)){
                ShellCredential compare=(ShellCredential)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Key.ToString();
        }

        public string DescriptorColumn() {
            return "Key";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Key";
        }
        
        #region ' Foreign Keys '
		private List<Shell> _Shells
        {
            get
            {            
				IRepository<Shell> repo = RingCast.Shell.GetRepo();
				Expression<Func<Shell, bool>> expression = x => x.Id == ShellId;
				CachedDataLoader<Shell>.DataRequest dataRequest 
				= new CachedDataLoader<Shell>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Shells", repo, expression);

				return CachedDataLoader<Shell>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		
		private List<ClientShellCredential> _ClientShellCredentials;
		public List<ClientShellCredential> ClientShellCredentials
        {
            get
            {            
				IRepository<ClientShellCredential> repo = RingCast.ClientShellCredential.GetRepo();
				Expression<Func<ClientShellCredential, bool>> expression = x => x.ShellCredentialId == Id;
				CachedDataLoader<ClientShellCredential>.DataRequest dataRequest 
				= new CachedDataLoader<ClientShellCredential>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "ClientShellCredentials", repo, expression);

				return CachedDataLoader<ClientShellCredential>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _ClientShellCredentials = value;
               
               OnChanged();
            }
        }
		
		
		public Shell Shell
		{
			get
			{
				return _Shells.SingleOrDefault(x => x.Id == _ShellId);
			}								
			set
			{
				ShellId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _ShellId;
		 [XmlIgnore] 
        public int ShellId
        {
            get { return _ShellId; }
            set
            {
                if(_ShellId!=value){
                    _ShellId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShellId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Key;
		  
        public string Key
        {
            get { return _Key; }
            set
            {
                if(_Key!=value){
                    _Key=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Key");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _DefaultValue;
		  
        public string DefaultValue
        {
            get { return _DefaultValue; }
            set
            {
                if(_DefaultValue!=value){
                    _DefaultValue=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="DefaultValue");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (ClientShellCredentials != null && ClientShellCredentials.Count > 0)
				ClientShellCredentials.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (ClientShellCredentials != null && ClientShellCredentials.Count > 0)
				ClientShellCredentials.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            ShellCredential item = new ShellCredential(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(ShellCredential shellCredential){
			
			if (shellCredential != null)
			{
				try 
				{
					
					this.Id = shellCredential.Id;
					
										
					this.ShellId = shellCredential.ShellId;
					
										
					this.Key = shellCredential.Key;
					
										
					this.DefaultValue = shellCredential.DefaultValue;
					
										
					this.CreatedOn = shellCredential.CreatedOn;
					
										
					this.CreatedBy = shellCredential.CreatedBy;
					
										
					this.ModifiedOn = shellCredential.ModifiedOn;
					
										
					this.ModifiedBy = shellCredential.ModifiedBy;
					
										
					this.IsDeleted = shellCredential.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public ShellCredential(ShellCredential shellCredential):this() {

			Load(shellCredential);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<ShellCredential, bool>> expression) {
            var repo = GetRepo();
            
            
            List<ShellCredential> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<ShellCredential, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the MessageStatuses table in the RingCast Database.
    /// </summary>
    public partial class _MessageStatus: BusinessObject<_MessageStatus>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<_MessageStatus>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<_MessageStatus> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<_MessageStatus>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<_MessageStatus> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(_MessageStatus item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                _MessageStatus item=new _MessageStatus();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<_MessageStatus> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public _MessageStatus(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                _MessageStatus.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_MessageStatus>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public _MessageStatus(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public _MessageStatus(Expression<Func<_MessageStatus, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<_MessageStatus> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<_MessageStatus> _repo;
            
            if(db.TestMode){
                _MessageStatus.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_MessageStatus>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<_MessageStatus> GetRepo(){
            return GetRepo("","");
        }
        
        public static _MessageStatus SingleOrDefault(Expression<Func<_MessageStatus, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            _MessageStatus single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static _MessageStatus SingleOrDefault(Expression<Func<_MessageStatus, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            _MessageStatus single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<_MessageStatus, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<_MessageStatus, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<_MessageStatus> Find(Expression<Func<_MessageStatus, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<_MessageStatus> Find(Expression<Func<_MessageStatus, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<_MessageStatus> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<_MessageStatus> All() {
            return GetRepo().GetAll();
        }

		public static List<_MessageStatus> FetchAll(string connectionString, string providerName) 
		{
            IRepository<_MessageStatus> repo = RingCast._MessageStatus.GetRepo(connectionString,providerName);
			CachedDataLoader<_MessageStatus>.DataRequest dataRequest 
			= new CachedDataLoader<_MessageStatus>.DataRequest("RingCast", connectionString, "MessageStatuses", repo);

			return CachedDataLoader<_MessageStatus>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<_MessageStatus> FetchAll(Expression<Func<_MessageStatus, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<_MessageStatus> repo = RingCast._MessageStatus.GetRepo();
			CachedDataLoader<_MessageStatus>.DataRequest dataRequest 
			= new CachedDataLoader<_MessageStatus>.DataRequest("RingCast", db.DataProvider.ConnectionString, "MessageStatuses", repo, expression);

			return CachedDataLoader<_MessageStatus>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<_MessageStatus> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<_MessageStatus> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<_MessageStatus> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<_MessageStatus> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<_MessageStatus> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(_MessageStatus)){
                _MessageStatus compare=(_MessageStatus)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<MessageHistory> _MessageHistories;
		public List<MessageHistory> MessageHistories
        {
            get
            {            
				IRepository<MessageHistory> repo = RingCast.MessageHistory.GetRepo();
				Expression<Func<MessageHistory, bool>> expression = x => x.MessageStatusId == Id;
				CachedDataLoader<MessageHistory>.DataRequest dataRequest 
				= new CachedDataLoader<MessageHistory>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "MessageHistory", repo, expression);

				return CachedDataLoader<MessageHistory>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _MessageHistories = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<Message> _Messages;
		public List<Message> Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.MessageStatusId == Id;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Messages = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (MessageHistories != null && MessageHistories.Count > 0)
				MessageHistories.ForEach(x => x.Save(provider));	
				
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (MessageHistories != null && MessageHistories.Count > 0)
				MessageHistories.ForEach(x => x.Save(username, provider));
				
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            _MessageStatus item = new _MessageStatus(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(_MessageStatus _MessageStatus){
			
			if (_MessageStatus != null)
			{
				try 
				{
					
					this.Id = _MessageStatus.Id;
					
										
					this.Name = _MessageStatus.Name;
					
										
					this.CreatedOn = _MessageStatus.CreatedOn;
					
										
					this.CreatedBy = _MessageStatus.CreatedBy;
					
										
					this.ModifiedOn = _MessageStatus.ModifiedOn;
					
										
					this.ModifiedBy = _MessageStatus.ModifiedBy;
					
										
					this.IsDeleted = _MessageStatus.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public _MessageStatus(_MessageStatus _MessageStatus):this() {

			Load(_MessageStatus);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<_MessageStatus, bool>> expression) {
            var repo = GetRepo();
            
            
            List<_MessageStatus> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<_MessageStatus, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the Campaigns table in the RingCast Database.
    /// </summary>
    public partial class Campaign: BusinessObject<Campaign>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<Campaign>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<Campaign> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<Campaign>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<Campaign> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(Campaign item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                Campaign item=new Campaign();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<Campaign> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public Campaign(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                Campaign.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Campaign>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public Campaign(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public Campaign(Expression<Func<Campaign, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<Campaign> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<Campaign> _repo;
            
            if(db.TestMode){
                Campaign.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Campaign>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<Campaign> GetRepo(){
            return GetRepo("","");
        }
        
        public static Campaign SingleOrDefault(Expression<Func<Campaign, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            Campaign single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static Campaign SingleOrDefault(Expression<Func<Campaign, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            Campaign single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<Campaign, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<Campaign, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<Campaign> Find(Expression<Func<Campaign, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<Campaign> Find(Expression<Func<Campaign, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<Campaign> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<Campaign> All() {
            return GetRepo().GetAll();
        }

		public static List<Campaign> FetchAll(string connectionString, string providerName) 
		{
            IRepository<Campaign> repo = RingCast.Campaign.GetRepo(connectionString,providerName);
			CachedDataLoader<Campaign>.DataRequest dataRequest 
			= new CachedDataLoader<Campaign>.DataRequest("RingCast", connectionString, "Campaigns", repo);

			return CachedDataLoader<Campaign>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<Campaign> FetchAll(Expression<Func<Campaign, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<Campaign> repo = RingCast.Campaign.GetRepo();
			CachedDataLoader<Campaign>.DataRequest dataRequest 
			= new CachedDataLoader<Campaign>.DataRequest("RingCast", db.DataProvider.ConnectionString, "Campaigns", repo, expression);

			return CachedDataLoader<Campaign>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<Campaign> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<Campaign> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<Campaign> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<Campaign> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<Campaign> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(Campaign)){
                Campaign compare=(Campaign)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		private List<Client> _Clients
        {
            get
            {            
				IRepository<Client> repo = RingCast.Client.GetRepo();
				Expression<Func<Client, bool>> expression = x => x.Id == ClientId;
				CachedDataLoader<Client>.DataRequest dataRequest 
				= new CachedDataLoader<Client>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Clients", repo, expression);

				return CachedDataLoader<Client>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		
		private List<CampaignIdentifierPool> _IdentifierPools;
		public List<CampaignIdentifierPool> IdentifierPools
        {
            get
            {            
				IRepository<CampaignIdentifierPool> repo = RingCast.CampaignIdentifierPool.GetRepo();
				Expression<Func<CampaignIdentifierPool, bool>> expression = x => x.CampaignId == Id;
				CachedDataLoader<CampaignIdentifierPool>.DataRequest dataRequest 
				= new CachedDataLoader<CampaignIdentifierPool>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "CampaignIdentifierPool", repo, expression);

				return CachedDataLoader<CampaignIdentifierPool>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _IdentifierPools = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<PipeCampaignKeyword> _PipeCampaignKeywords;
		public List<PipeCampaignKeyword> PipeCampaignKeywords
        {
            get
            {            
				IRepository<PipeCampaignKeyword> repo = RingCast.PipeCampaignKeyword.GetRepo();
				Expression<Func<PipeCampaignKeyword, bool>> expression = x => x.CampaignId == Id;
				CachedDataLoader<PipeCampaignKeyword>.DataRequest dataRequest 
				= new CachedDataLoader<PipeCampaignKeyword>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "PipeCampaignKeywords", repo, expression);

				return CachedDataLoader<PipeCampaignKeyword>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _PipeCampaignKeywords = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<Session> _Sessions;
		public List<Session> Sessions
        {
            get
            {            
				IRepository<Session> repo = RingCast.Session.GetRepo();
				Expression<Func<Session, bool>> expression = x => x.CampaignId == Id;
				CachedDataLoader<Session>.DataRequest dataRequest 
				= new CachedDataLoader<Session>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Sessions", repo, expression);

				return CachedDataLoader<Session>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Sessions = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<CampaignShell> _Shells;
		public List<CampaignShell> Shells
        {
            get
            {            
				IRepository<CampaignShell> repo = RingCast.CampaignShell.GetRepo();
				Expression<Func<CampaignShell, bool>> expression = x => x.CampaignId == Id;
				CachedDataLoader<CampaignShell>.DataRequest dataRequest 
				= new CachedDataLoader<CampaignShell>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "CampaignShells", repo, expression);

				return CachedDataLoader<CampaignShell>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Shells = value;
               
               OnChanged();
            }
        }
		
		
		public Client Client
		{
			get
			{
				return _Clients.SingleOrDefault(x => x.Id == _ClientId);
			}								
			set
			{
				ClientId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _ClientId;
		 [XmlIgnore] 
        public int ClientId
        {
            get { return _ClientId; }
            set
            {
                if(_ClientId!=value){
                    _ClientId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ClientId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Description;
		  
        public string Description
        {
            get { return _Description; }
            set
            {
                if(_Description!=value){
                    _Description=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Description");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _StartDate;
		  
        public DateTime StartDate
        {
            get { return _StartDate; }
            set
            {
                if(_StartDate!=value){
                    _StartDate=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="StartDate");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _EndDate;
		  
        public DateTime EndDate
        {
            get { return _EndDate; }
            set
            {
                if(_EndDate!=value){
                    _EndDate=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EndDate");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _AutoResponseMessage;
		  
        public string AutoResponseMessage
        {
            get { return _AutoResponseMessage; }
            set
            {
                if(_AutoResponseMessage!=value){
                    _AutoResponseMessage=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="AutoResponseMessage");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsEnabled;
		  
        public bool IsEnabled
        {
            get { return _IsEnabled; }
            set
            {
                if(_IsEnabled!=value){
                    _IsEnabled=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsEnabled");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (IdentifierPools != null && IdentifierPools.Count > 0)
				IdentifierPools.ForEach(x => x.Save(provider));	
				
			
			if (PipeCampaignKeywords != null && PipeCampaignKeywords.Count > 0)
				PipeCampaignKeywords.ForEach(x => x.Save(provider));	
				
			
			if (Sessions != null && Sessions.Count > 0)
				Sessions.ForEach(x => x.Save(provider));	
				
			
			if (Shells != null && Shells.Count > 0)
				Shells.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (IdentifierPools != null && IdentifierPools.Count > 0)
				IdentifierPools.ForEach(x => x.Save(username, provider));
				
			
			if (PipeCampaignKeywords != null && PipeCampaignKeywords.Count > 0)
				PipeCampaignKeywords.ForEach(x => x.Save(username, provider));
				
			
			if (Sessions != null && Sessions.Count > 0)
				Sessions.ForEach(x => x.Save(username, provider));
				
			
			if (Shells != null && Shells.Count > 0)
				Shells.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            Campaign item = new Campaign(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(Campaign campaign){
			
			if (campaign != null)
			{
				try 
				{
					
					this.Id = campaign.Id;
					
										
					this.ClientId = campaign.ClientId;
					
										
					this.Name = campaign.Name;
					
										
					this.Description = campaign.Description;
					
										
					this.StartDate = campaign.StartDate;
					
										
					this.EndDate = campaign.EndDate;
					
										
					this.AutoResponseMessage = campaign.AutoResponseMessage;
					
										
					this.IsEnabled = campaign.IsEnabled;
					
										
					this.CreatedOn = campaign.CreatedOn;
					
										
					this.CreatedBy = campaign.CreatedBy;
					
										
					this.ModifiedOn = campaign.ModifiedOn;
					
										
					this.ModifiedBy = campaign.ModifiedBy;
					
										
					this.IsDeleted = campaign.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public Campaign(Campaign campaign):this() {

			Load(campaign);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<Campaign, bool>> expression) {
            var repo = GetRepo();
            
            
            List<Campaign> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<Campaign, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the Gateways table in the RingCast Database.
    /// </summary>
    public partial class Gateway: BusinessObject<Gateway>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<Gateway>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<Gateway> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<Gateway>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<Gateway> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(Gateway item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                Gateway item=new Gateway();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<Gateway> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public Gateway(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                Gateway.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Gateway>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public Gateway(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public Gateway(Expression<Func<Gateway, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<Gateway> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<Gateway> _repo;
            
            if(db.TestMode){
                Gateway.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Gateway>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<Gateway> GetRepo(){
            return GetRepo("","");
        }
        
        public static Gateway SingleOrDefault(Expression<Func<Gateway, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            Gateway single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static Gateway SingleOrDefault(Expression<Func<Gateway, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            Gateway single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<Gateway, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<Gateway, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<Gateway> Find(Expression<Func<Gateway, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<Gateway> Find(Expression<Func<Gateway, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<Gateway> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<Gateway> All() {
            return GetRepo().GetAll();
        }

		public static List<Gateway> FetchAll(string connectionString, string providerName) 
		{
            IRepository<Gateway> repo = RingCast.Gateway.GetRepo(connectionString,providerName);
			CachedDataLoader<Gateway>.DataRequest dataRequest 
			= new CachedDataLoader<Gateway>.DataRequest("RingCast", connectionString, "Gateways", repo);

			return CachedDataLoader<Gateway>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<Gateway> FetchAll(Expression<Func<Gateway, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<Gateway> repo = RingCast.Gateway.GetRepo();
			CachedDataLoader<Gateway>.DataRequest dataRequest 
			= new CachedDataLoader<Gateway>.DataRequest("RingCast", db.DataProvider.ConnectionString, "Gateways", repo, expression);

			return CachedDataLoader<Gateway>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<Gateway> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<Gateway> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<Gateway> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<Gateway> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<Gateway> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(Gateway)){
                Gateway compare=(Gateway)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<GatewayCredential> _Credentials;
		public List<GatewayCredential> Credentials
        {
            get
            {            
				IRepository<GatewayCredential> repo = RingCast.GatewayCredential.GetRepo();
				Expression<Func<GatewayCredential, bool>> expression = x => x.GatewayId == Id;
				CachedDataLoader<GatewayCredential>.DataRequest dataRequest 
				= new CachedDataLoader<GatewayCredential>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "GatewayCredentials", repo, expression);

				return CachedDataLoader<GatewayCredential>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Credentials = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<GatewayIP> _IPs;
		public List<GatewayIP> IPs
        {
            get
            {            
				IRepository<GatewayIP> repo = RingCast.GatewayIP.GetRepo();
				Expression<Func<GatewayIP, bool>> expression = x => x.GatewayId == Id;
				CachedDataLoader<GatewayIP>.DataRequest dataRequest 
				= new CachedDataLoader<GatewayIP>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "GatewayIPs", repo, expression);

				return CachedDataLoader<GatewayIP>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _IPs = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<Message> _Messages;
		public List<Message> Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.GatewayId == Id;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Messages = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<OutboundGatewayCountry> _OutboundGatewayCountries;
		public List<OutboundGatewayCountry> OutboundGatewayCountries
        {
            get
            {            
				IRepository<OutboundGatewayCountry> repo = RingCast.OutboundGatewayCountry.GetRepo();
				Expression<Func<OutboundGatewayCountry, bool>> expression = x => x.GatewayId == Id;
				CachedDataLoader<OutboundGatewayCountry>.DataRequest dataRequest 
				= new CachedDataLoader<OutboundGatewayCountry>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "OutboundGatewayCountries", repo, expression);

				return CachedDataLoader<OutboundGatewayCountry>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _OutboundGatewayCountries = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<Pipe> _Pipes;
		public List<Pipe> Pipes
        {
            get
            {            
				IRepository<Pipe> repo = RingCast.Pipe.GetRepo();
				Expression<Func<Pipe, bool>> expression = x => x.InboundGatewayId == Id;
				CachedDataLoader<Pipe>.DataRequest dataRequest 
				= new CachedDataLoader<Pipe>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Pipes", repo, expression);

				return CachedDataLoader<Pipe>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Pipes = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ProviderName;
		  
        public string ProviderName
        {
            get { return _ProviderName; }
            set
            {
                if(_ProviderName!=value){
                    _ProviderName=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ProviderName");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ProviderType;
		  
        public string ProviderType
        {
            get { return _ProviderType; }
            set
            {
                if(_ProviderType!=value){
                    _ProviderType=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ProviderType");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsOutboundDefault;
		  
        public bool IsOutboundDefault
        {
            get { return _IsOutboundDefault; }
            set
            {
                if(_IsOutboundDefault!=value){
                    _IsOutboundDefault=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsOutboundDefault");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsEnabled;
		  
        public bool IsEnabled
        {
            get { return _IsEnabled; }
            set
            {
                if(_IsEnabled!=value){
                    _IsEnabled=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsEnabled");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Credentials != null && Credentials.Count > 0)
				Credentials.ForEach(x => x.Save(provider));	
				
			
			if (IPs != null && IPs.Count > 0)
				IPs.ForEach(x => x.Save(provider));	
				
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(provider));	
				
			
			if (OutboundGatewayCountries != null && OutboundGatewayCountries.Count > 0)
				OutboundGatewayCountries.ForEach(x => x.Save(provider));	
				
			
			if (Pipes != null && Pipes.Count > 0)
				Pipes.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Credentials != null && Credentials.Count > 0)
				Credentials.ForEach(x => x.Save(username, provider));
				
			
			if (IPs != null && IPs.Count > 0)
				IPs.ForEach(x => x.Save(username, provider));
				
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(username, provider));
				
			
			if (OutboundGatewayCountries != null && OutboundGatewayCountries.Count > 0)
				OutboundGatewayCountries.ForEach(x => x.Save(username, provider));
				
			
			if (Pipes != null && Pipes.Count > 0)
				Pipes.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            Gateway item = new Gateway(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(Gateway gateway){
			
			if (gateway != null)
			{
				try 
				{
					
					this.Id = gateway.Id;
					
										
					this.Name = gateway.Name;
					
										
					this.ProviderName = gateway.ProviderName;
					
										
					this.ProviderType = gateway.ProviderType;
					
										
					this.IsOutboundDefault = gateway.IsOutboundDefault;
					
										
					this.IsEnabled = gateway.IsEnabled;
					
										
					this.CreatedOn = gateway.CreatedOn;
					
										
					this.CreatedBy = gateway.CreatedBy;
					
										
					this.ModifiedOn = gateway.ModifiedOn;
					
										
					this.ModifiedBy = gateway.ModifiedBy;
					
										
					this.IsDeleted = gateway.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public Gateway(Gateway gateway):this() {

			Load(gateway);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<Gateway, bool>> expression) {
            var repo = GetRepo();
            
            
            List<Gateway> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<Gateway, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the ClientShellCredentials table in the RingCast Database.
    /// </summary>
    public partial class ClientShellCredential: BusinessObject<ClientShellCredential>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<ClientShellCredential>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<ClientShellCredential> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<ClientShellCredential>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<ClientShellCredential> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(ClientShellCredential item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                ClientShellCredential item=new ClientShellCredential();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<ClientShellCredential> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public ClientShellCredential(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                ClientShellCredential.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<ClientShellCredential>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public ClientShellCredential(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public ClientShellCredential(Expression<Func<ClientShellCredential, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<ClientShellCredential> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<ClientShellCredential> _repo;
            
            if(db.TestMode){
                ClientShellCredential.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<ClientShellCredential>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<ClientShellCredential> GetRepo(){
            return GetRepo("","");
        }
        
        public static ClientShellCredential SingleOrDefault(Expression<Func<ClientShellCredential, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            ClientShellCredential single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static ClientShellCredential SingleOrDefault(Expression<Func<ClientShellCredential, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            ClientShellCredential single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<ClientShellCredential, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<ClientShellCredential, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<ClientShellCredential> Find(Expression<Func<ClientShellCredential, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<ClientShellCredential> Find(Expression<Func<ClientShellCredential, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<ClientShellCredential> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<ClientShellCredential> All() {
            return GetRepo().GetAll();
        }

		public static List<ClientShellCredential> FetchAll(string connectionString, string providerName) 
		{
            IRepository<ClientShellCredential> repo = RingCast.ClientShellCredential.GetRepo(connectionString,providerName);
			CachedDataLoader<ClientShellCredential>.DataRequest dataRequest 
			= new CachedDataLoader<ClientShellCredential>.DataRequest("RingCast", connectionString, "ClientShellCredentials", repo);

			return CachedDataLoader<ClientShellCredential>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<ClientShellCredential> FetchAll(Expression<Func<ClientShellCredential, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<ClientShellCredential> repo = RingCast.ClientShellCredential.GetRepo();
			CachedDataLoader<ClientShellCredential>.DataRequest dataRequest 
			= new CachedDataLoader<ClientShellCredential>.DataRequest("RingCast", db.DataProvider.ConnectionString, "ClientShellCredentials", repo, expression);

			return CachedDataLoader<ClientShellCredential>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<ClientShellCredential> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<ClientShellCredential> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<ClientShellCredential> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<ClientShellCredential> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<ClientShellCredential> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Value.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(ClientShellCredential)){
                ClientShellCredential compare=(ClientShellCredential)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Value.ToString();
        }

        public string DescriptorColumn() {
            return "Value";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Value";
        }
        
        #region ' Foreign Keys '
		private List<Client> _Clients
        {
            get
            {            
				IRepository<Client> repo = RingCast.Client.GetRepo();
				Expression<Func<Client, bool>> expression = x => x.Id == ClientId;
				CachedDataLoader<Client>.DataRequest dataRequest 
				= new CachedDataLoader<Client>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Clients", repo, expression);

				return CachedDataLoader<Client>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<ShellCredential> _ShellCredentials
        {
            get
            {            
				IRepository<ShellCredential> repo = RingCast.ShellCredential.GetRepo();
				Expression<Func<ShellCredential, bool>> expression = x => x.Id == ShellCredentialId;
				CachedDataLoader<ShellCredential>.DataRequest dataRequest 
				= new CachedDataLoader<ShellCredential>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "ShellCredentials", repo, expression);

				return CachedDataLoader<ShellCredential>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Client Client
		{
			get
			{
				return _Clients.SingleOrDefault(x => x.Id == _ClientId);
			}								
			set
			{
				ClientId = value.Id;
			}
		}

		public ShellCredential ShellCredential
		{
			get
			{
				return _ShellCredentials.SingleOrDefault(x => x.Id == _ShellCredentialId);
			}								
			set
			{
				ShellCredentialId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _ClientId;
		 [XmlIgnore] 
        public int ClientId
        {
            get { return _ClientId; }
            set
            {
                if(_ClientId!=value){
                    _ClientId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ClientId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _ShellCredentialId;
		 [XmlIgnore] 
        public int ShellCredentialId
        {
            get { return _ShellCredentialId; }
            set
            {
                if(_ShellCredentialId!=value){
                    _ShellCredentialId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShellCredentialId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Value;
		  
        public string Value
        {
            get { return _Value; }
            set
            {
                if(_Value!=value){
                    _Value=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Value");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            ClientShellCredential item = new ClientShellCredential(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(ClientShellCredential clientShellCredential){
			
			if (clientShellCredential != null)
			{
				try 
				{
					
					this.Id = clientShellCredential.Id;
					
										
					this.ClientId = clientShellCredential.ClientId;
					
										
					this.ShellCredentialId = clientShellCredential.ShellCredentialId;
					
										
					this.Value = clientShellCredential.Value;
					
										
					this.CreatedOn = clientShellCredential.CreatedOn;
					
										
					this.CreatedBy = clientShellCredential.CreatedBy;
					
										
					this.ModifiedOn = clientShellCredential.ModifiedOn;
					
										
					this.ModifiedBy = clientShellCredential.ModifiedBy;
					
										
					this.IsDeleted = clientShellCredential.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public ClientShellCredential(ClientShellCredential clientShellCredential):this() {

			Load(clientShellCredential);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<ClientShellCredential, bool>> expression) {
            var repo = GetRepo();
            
            
            List<ClientShellCredential> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<ClientShellCredential, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the MessageDirections table in the RingCast Database.
    /// </summary>
    public partial class _MessageDirection: BusinessObject<_MessageDirection>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<_MessageDirection>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<_MessageDirection> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<_MessageDirection>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<_MessageDirection> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(_MessageDirection item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                _MessageDirection item=new _MessageDirection();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<_MessageDirection> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public _MessageDirection(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                _MessageDirection.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_MessageDirection>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public _MessageDirection(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public _MessageDirection(Expression<Func<_MessageDirection, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<_MessageDirection> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<_MessageDirection> _repo;
            
            if(db.TestMode){
                _MessageDirection.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_MessageDirection>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<_MessageDirection> GetRepo(){
            return GetRepo("","");
        }
        
        public static _MessageDirection SingleOrDefault(Expression<Func<_MessageDirection, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            _MessageDirection single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static _MessageDirection SingleOrDefault(Expression<Func<_MessageDirection, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            _MessageDirection single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<_MessageDirection, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<_MessageDirection, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<_MessageDirection> Find(Expression<Func<_MessageDirection, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<_MessageDirection> Find(Expression<Func<_MessageDirection, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<_MessageDirection> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<_MessageDirection> All() {
            return GetRepo().GetAll();
        }

		public static List<_MessageDirection> FetchAll(string connectionString, string providerName) 
		{
            IRepository<_MessageDirection> repo = RingCast._MessageDirection.GetRepo(connectionString,providerName);
			CachedDataLoader<_MessageDirection>.DataRequest dataRequest 
			= new CachedDataLoader<_MessageDirection>.DataRequest("RingCast", connectionString, "MessageDirections", repo);

			return CachedDataLoader<_MessageDirection>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<_MessageDirection> FetchAll(Expression<Func<_MessageDirection, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<_MessageDirection> repo = RingCast._MessageDirection.GetRepo();
			CachedDataLoader<_MessageDirection>.DataRequest dataRequest 
			= new CachedDataLoader<_MessageDirection>.DataRequest("RingCast", db.DataProvider.ConnectionString, "MessageDirections", repo, expression);

			return CachedDataLoader<_MessageDirection>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<_MessageDirection> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<_MessageDirection> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<_MessageDirection> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<_MessageDirection> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<_MessageDirection> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(_MessageDirection)){
                _MessageDirection compare=(_MessageDirection)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<Message> _Messages;
		public List<Message> Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.MessageDirectionId == Id;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Messages = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            _MessageDirection item = new _MessageDirection(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(_MessageDirection _MessageDirection){
			
			if (_MessageDirection != null)
			{
				try 
				{
					
					this.Id = _MessageDirection.Id;
					
										
					this.Name = _MessageDirection.Name;
					
										
					this.CreatedOn = _MessageDirection.CreatedOn;
					
										
					this.CreatedBy = _MessageDirection.CreatedBy;
					
										
					this.ModifiedOn = _MessageDirection.ModifiedOn;
					
										
					this.ModifiedBy = _MessageDirection.ModifiedBy;
					
										
					this.IsDeleted = _MessageDirection.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public _MessageDirection(_MessageDirection _MessageDirection):this() {

			Load(_MessageDirection);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<_MessageDirection, bool>> expression) {
            var repo = GetRepo();
            
            
            List<_MessageDirection> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<_MessageDirection, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the InterfaceResults table in the RingCast Database.
    /// </summary>
    public partial class InterfaceResult: BusinessObject<InterfaceResult>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<InterfaceResult>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<InterfaceResult> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<InterfaceResult>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<InterfaceResult> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(InterfaceResult item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                InterfaceResult item=new InterfaceResult();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<InterfaceResult> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public InterfaceResult(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                InterfaceResult.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<InterfaceResult>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public InterfaceResult(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public InterfaceResult(Expression<Func<InterfaceResult, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<InterfaceResult> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<InterfaceResult> _repo;
            
            if(db.TestMode){
                InterfaceResult.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<InterfaceResult>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<InterfaceResult> GetRepo(){
            return GetRepo("","");
        }
        
        public static InterfaceResult SingleOrDefault(Expression<Func<InterfaceResult, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            InterfaceResult single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static InterfaceResult SingleOrDefault(Expression<Func<InterfaceResult, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            InterfaceResult single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<InterfaceResult, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<InterfaceResult, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<InterfaceResult> Find(Expression<Func<InterfaceResult, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<InterfaceResult> Find(Expression<Func<InterfaceResult, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<InterfaceResult> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<InterfaceResult> All() {
            return GetRepo().GetAll();
        }

		public static List<InterfaceResult> FetchAll(string connectionString, string providerName) 
		{
            IRepository<InterfaceResult> repo = RingCast.InterfaceResult.GetRepo(connectionString,providerName);
			CachedDataLoader<InterfaceResult>.DataRequest dataRequest 
			= new CachedDataLoader<InterfaceResult>.DataRequest("RingCast", connectionString, "InterfaceResults", repo);

			return CachedDataLoader<InterfaceResult>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<InterfaceResult> FetchAll(Expression<Func<InterfaceResult, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<InterfaceResult> repo = RingCast.InterfaceResult.GetRepo();
			CachedDataLoader<InterfaceResult>.DataRequest dataRequest 
			= new CachedDataLoader<InterfaceResult>.DataRequest("RingCast", db.DataProvider.ConnectionString, "InterfaceResults", repo, expression);

			return CachedDataLoader<InterfaceResult>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<InterfaceResult> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<InterfaceResult> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<InterfaceResult> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<InterfaceResult> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<InterfaceResult> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.ResultMessage.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(InterfaceResult)){
                InterfaceResult compare=(InterfaceResult)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.ResultMessage.ToString();
        }

        public string DescriptorColumn() {
            return "ResultMessage";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "ResultMessage";
        }
        
        #region ' Foreign Keys '
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _ResultCode;
		  
        public int ResultCode
        {
            get { return _ResultCode; }
            set
            {
                if(_ResultCode!=value){
                    _ResultCode=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ResultCode");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ResultMessage;
		  
        public string ResultMessage
        {
            get { return _ResultMessage; }
            set
            {
                if(_ResultMessage!=value){
                    _ResultMessage=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ResultMessage");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _Created;
		  
        public DateTime Created
        {
            get { return _Created; }
            set
            {
                if(_Created!=value){
                    _Created=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Created");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _LastModified;
		  
        public DateTime LastModified
        {
            get { return _LastModified; }
            set
            {
                if(_LastModified!=value){
                    _LastModified=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="LastModified");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            InterfaceResult item = new InterfaceResult(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(InterfaceResult interfaceResult){
			
			if (interfaceResult != null)
			{
				try 
				{
					
					this.Id = interfaceResult.Id;
					
										
					this.ResultCode = interfaceResult.ResultCode;
					
										
					this.ResultMessage = interfaceResult.ResultMessage;
					
										
					this.Created = interfaceResult.Created;
					
										
					this.LastModified = interfaceResult.LastModified;
					
										
					this.CreatedOn = interfaceResult.CreatedOn;
					
										
					this.CreatedBy = interfaceResult.CreatedBy;
					
										
					this.ModifiedOn = interfaceResult.ModifiedOn;
					
										
					this.ModifiedBy = interfaceResult.ModifiedBy;
					
										
					this.IsDeleted = interfaceResult.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public InterfaceResult(InterfaceResult interfaceResult):this() {

			Load(interfaceResult);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<InterfaceResult, bool>> expression) {
            var repo = GetRepo();
            
            
            List<InterfaceResult> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<InterfaceResult, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the CampaignShells table in the RingCast Database.
    /// </summary>
    public partial class CampaignShell: BusinessObject<CampaignShell>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<CampaignShell>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<CampaignShell> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<CampaignShell>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<CampaignShell> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(CampaignShell item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                CampaignShell item=new CampaignShell();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<CampaignShell> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public CampaignShell(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                CampaignShell.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<CampaignShell>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public CampaignShell(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public CampaignShell(Expression<Func<CampaignShell, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<CampaignShell> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<CampaignShell> _repo;
            
            if(db.TestMode){
                CampaignShell.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<CampaignShell>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<CampaignShell> GetRepo(){
            return GetRepo("","");
        }
        
        public static CampaignShell SingleOrDefault(Expression<Func<CampaignShell, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            CampaignShell single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static CampaignShell SingleOrDefault(Expression<Func<CampaignShell, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            CampaignShell single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<CampaignShell, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<CampaignShell, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<CampaignShell> Find(Expression<Func<CampaignShell, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<CampaignShell> Find(Expression<Func<CampaignShell, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<CampaignShell> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<CampaignShell> All() {
            return GetRepo().GetAll();
        }

		public static List<CampaignShell> FetchAll(string connectionString, string providerName) 
		{
            IRepository<CampaignShell> repo = RingCast.CampaignShell.GetRepo(connectionString,providerName);
			CachedDataLoader<CampaignShell>.DataRequest dataRequest 
			= new CachedDataLoader<CampaignShell>.DataRequest("RingCast", connectionString, "CampaignShells", repo);

			return CachedDataLoader<CampaignShell>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<CampaignShell> FetchAll(Expression<Func<CampaignShell, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<CampaignShell> repo = RingCast.CampaignShell.GetRepo();
			CachedDataLoader<CampaignShell>.DataRequest dataRequest 
			= new CachedDataLoader<CampaignShell>.DataRequest("RingCast", db.DataProvider.ConnectionString, "CampaignShells", repo, expression);

			return CachedDataLoader<CampaignShell>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<CampaignShell> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<CampaignShell> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<CampaignShell> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<CampaignShell> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<CampaignShell> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.CreatedBy.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(CampaignShell)){
                CampaignShell compare=(CampaignShell)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.CreatedBy.ToString();
        }

        public string DescriptorColumn() {
            return "CreatedBy";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "CreatedBy";
        }
        
        #region ' Foreign Keys '
		private List<Campaign> _Campaigns
        {
            get
            {            
				IRepository<Campaign> repo = RingCast.Campaign.GetRepo();
				Expression<Func<Campaign, bool>> expression = x => x.Id == CampaignId;
				CachedDataLoader<Campaign>.DataRequest dataRequest 
				= new CachedDataLoader<Campaign>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Campaigns", repo, expression);

				return CachedDataLoader<Campaign>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<Shell> _Shells
        {
            get
            {            
				IRepository<Shell> repo = RingCast.Shell.GetRepo();
				Expression<Func<Shell, bool>> expression = x => x.Id == ShellId;
				CachedDataLoader<Shell>.DataRequest dataRequest 
				= new CachedDataLoader<Shell>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Shells", repo, expression);

				return CachedDataLoader<Shell>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Campaign Campaign
		{
			get
			{
				return _Campaigns.SingleOrDefault(x => x.Id == _CampaignId);
			}								
			set
			{
				CampaignId = value.Id;
			}
		}

		public Shell Shell
		{
			get
			{
				return _Shells.SingleOrDefault(x => x.Id == _ShellId);
			}								
			set
			{
				ShellId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _CampaignId;
		 [XmlIgnore] 
        public int CampaignId
        {
            get { return _CampaignId; }
            set
            {
                if(_CampaignId!=value){
                    _CampaignId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CampaignId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _ShellId;
		 [XmlIgnore] 
        public int ShellId
        {
            get { return _ShellId; }
            set
            {
                if(_ShellId!=value){
                    _ShellId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ShellId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _StartDate;
		  
        public DateTime StartDate
        {
            get { return _StartDate; }
            set
            {
                if(_StartDate!=value){
                    _StartDate=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="StartDate");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _EndDate;
		  
        public DateTime EndDate
        {
            get { return _EndDate; }
            set
            {
                if(_EndDate!=value){
                    _EndDate=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="EndDate");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            CampaignShell item = new CampaignShell(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(CampaignShell campaignShell){
			
			if (campaignShell != null)
			{
				try 
				{
					
					this.Id = campaignShell.Id;
					
										
					this.CampaignId = campaignShell.CampaignId;
					
										
					this.ShellId = campaignShell.ShellId;
					
										
					this.StartDate = campaignShell.StartDate;
					
										
					this.EndDate = campaignShell.EndDate;
					
										
					this.CreatedOn = campaignShell.CreatedOn;
					
										
					this.CreatedBy = campaignShell.CreatedBy;
					
										
					this.ModifiedOn = campaignShell.ModifiedOn;
					
										
					this.ModifiedBy = campaignShell.ModifiedBy;
					
										
					this.IsDeleted = campaignShell.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public CampaignShell(CampaignShell campaignShell):this() {

			Load(campaignShell);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<CampaignShell, bool>> expression) {
            var repo = GetRepo();
            
            
            List<CampaignShell> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<CampaignShell, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the Messages table in the RingCast Database.
    /// </summary>
    public partial class Message: BusinessObject<Message>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<Message>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<Message> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<Message>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<Message> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(Message item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                Message item=new Message();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<Message> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public Message(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                Message.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Message>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public Message(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public Message(Expression<Func<Message, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<Message> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<Message> _repo;
            
            if(db.TestMode){
                Message.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Message>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<Message> GetRepo(){
            return GetRepo("","");
        }
        
        public static Message SingleOrDefault(Expression<Func<Message, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            Message single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static Message SingleOrDefault(Expression<Func<Message, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            Message single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<Message, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<Message, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<Message> Find(Expression<Func<Message, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<Message> Find(Expression<Func<Message, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<Message> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<Message> All() {
            return GetRepo().GetAll();
        }

		public static List<Message> FetchAll(string connectionString, string providerName) 
		{
            IRepository<Message> repo = RingCast.Message.GetRepo(connectionString,providerName);
			CachedDataLoader<Message>.DataRequest dataRequest 
			= new CachedDataLoader<Message>.DataRequest("RingCast", connectionString, "Messages", repo);

			return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<Message> FetchAll(Expression<Func<Message, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<Message> repo = RingCast.Message.GetRepo();
			CachedDataLoader<Message>.DataRequest dataRequest 
			= new CachedDataLoader<Message>.DataRequest("RingCast", db.DataProvider.ConnectionString, "Messages", repo, expression);

			return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<Message> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<Message> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<Message> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<Message> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<Message> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.ClientReference.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(Message)){
                Message compare=(Message)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.ClientReference.ToString();
        }

        public string DescriptorColumn() {
            return "ClientReference";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "ClientReference";
        }
        
        #region ' Foreign Keys '
		private List<Customer> _Customers
        {
            get
            {            
				IRepository<Customer> repo = RingCast.Customer.GetRepo();
				Expression<Func<Customer, bool>> expression = x => x.Id == CustomerId;
				CachedDataLoader<Customer>.DataRequest dataRequest 
				= new CachedDataLoader<Customer>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Customers", repo, expression);

				return CachedDataLoader<Customer>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<Gateway> _Gateways
        {
            get
            {            
				IRepository<Gateway> repo = RingCast.Gateway.GetRepo();
				Expression<Func<Gateway, bool>> expression = x => x.Id == GatewayId;
				CachedDataLoader<Gateway>.DataRequest dataRequest 
				= new CachedDataLoader<Gateway>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Gateways", repo, expression);

				return CachedDataLoader<Gateway>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<MessageDirection> _MessageDirections
        {
            get
            {            
				IRepository<_MessageDirection> repo = RingCast._MessageDirection.GetRepo();
				Expression<Func<_MessageDirection, bool>> expression = x => x.Id == MessageDirectionId;
				CachedDataLoader<_MessageDirection>.DataRequest dataRequest 
				= new CachedDataLoader<_MessageDirection>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "MessageDirections", repo, expression);

				List<MessageDirection> list = new List<MessageDirection>();
				
				foreach (_MessageDirection item in CachedDataLoader<_MessageDirection>.GetCachedData(dataRequest).ToList())
				{
					list.Add((MessageDirection)item.Id);
				}
				
				return list;
            }
        }
		
		
		private List<MessageStatus> _MessageStatuses
        {
            get
            {            
				IRepository<_MessageStatus> repo = RingCast._MessageStatus.GetRepo();
				Expression<Func<_MessageStatus, bool>> expression = x => x.Id == MessageStatusId;
				CachedDataLoader<_MessageStatus>.DataRequest dataRequest 
				= new CachedDataLoader<_MessageStatus>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "MessageStatuses", repo, expression);

				List<MessageStatus> list = new List<MessageStatus>();
				
				foreach (_MessageStatus item in CachedDataLoader<_MessageStatus>.GetCachedData(dataRequest).ToList())
				{
					list.Add((MessageStatus)item.Id);
				}
				
				return list;
            }
        }
		
		
		private List<MessageType> _MessageTypes
        {
            get
            {            
				IRepository<_MessageType> repo = RingCast._MessageType.GetRepo();
				Expression<Func<_MessageType, bool>> expression = x => x.Id == MessageTypeId;
				CachedDataLoader<_MessageType>.DataRequest dataRequest 
				= new CachedDataLoader<_MessageType>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "MessageTypes", repo, expression);

				List<MessageType> list = new List<MessageType>();
				
				foreach (_MessageType item in CachedDataLoader<_MessageType>.GetCachedData(dataRequest).ToList())
				{
					list.Add((MessageType)item.Id);
				}
				
				return list;
            }
        }
		
		
		private List<Pipe> _Pipes
        {
            get
            {            
				IRepository<Pipe> repo = RingCast.Pipe.GetRepo();
				Expression<Func<Pipe, bool>> expression = x => x.Id == PipeId;
				CachedDataLoader<Pipe>.DataRequest dataRequest 
				= new CachedDataLoader<Pipe>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Pipes", repo, expression);

				return CachedDataLoader<Pipe>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<RequestLog> _RequestLogs
        {
            get
            {            
				IRepository<RequestLog> repo = RingCast.RequestLog.GetRepo();
				Expression<Func<RequestLog, bool>> expression = x => x.Id == RequestLogId;
				CachedDataLoader<RequestLog>.DataRequest dataRequest 
				= new CachedDataLoader<RequestLog>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "RequestLog", repo, expression);

				return CachedDataLoader<RequestLog>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<Session> _Sessions
        {
            get
            {            
				IRepository<Session> repo = RingCast.Session.GetRepo();
				Expression<Func<Session, bool>> expression = x => x.Id == SessionId;
				CachedDataLoader<Session>.DataRequest dataRequest 
				= new CachedDataLoader<Session>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Sessions", repo, expression);

				return CachedDataLoader<Session>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		
		private List<MessageAttachment> _Attachments;
		public List<MessageAttachment> Attachments
        {
            get
            {            
				IRepository<MessageAttachment> repo = RingCast.MessageAttachment.GetRepo();
				Expression<Func<MessageAttachment, bool>> expression = x => x.MessageId == Id;
				CachedDataLoader<MessageAttachment>.DataRequest dataRequest 
				= new CachedDataLoader<MessageAttachment>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "MessageAttachments", repo, expression);

				return CachedDataLoader<MessageAttachment>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Attachments = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<MessageHistory> _Histories;
		public List<MessageHistory> Histories
        {
            get
            {            
				IRepository<MessageHistory> repo = RingCast.MessageHistory.GetRepo();
				Expression<Func<MessageHistory, bool>> expression = x => x.MessageId == Id;
				CachedDataLoader<MessageHistory>.DataRequest dataRequest 
				= new CachedDataLoader<MessageHistory>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "MessageHistory", repo, expression);

				return CachedDataLoader<MessageHistory>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Histories = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<InboundMessageQueue> _InboundMessageQueues;
		public List<InboundMessageQueue> InboundMessageQueues
        {
            get
            {            
				IRepository<InboundMessageQueue> repo = RingCast.InboundMessageQueue.GetRepo();
				Expression<Func<InboundMessageQueue, bool>> expression = x => x.MessageId == Id;
				CachedDataLoader<InboundMessageQueue>.DataRequest dataRequest 
				= new CachedDataLoader<InboundMessageQueue>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "InboundMessageQueue", repo, expression);

				return CachedDataLoader<InboundMessageQueue>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _InboundMessageQueues = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<OutboundBatchMessage> _OutboundBatchMessages;
		public List<OutboundBatchMessage> OutboundBatchMessages
        {
            get
            {            
				IRepository<OutboundBatchMessage> repo = RingCast.OutboundBatchMessage.GetRepo();
				Expression<Func<OutboundBatchMessage, bool>> expression = x => x.MessageId == Id;
				CachedDataLoader<OutboundBatchMessage>.DataRequest dataRequest 
				= new CachedDataLoader<OutboundBatchMessage>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "OutboundBatchMessages", repo, expression);

				return CachedDataLoader<OutboundBatchMessage>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _OutboundBatchMessages = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<OutboundMessageQueue> _OutboundMessageQueues;
		public List<OutboundMessageQueue> OutboundMessageQueues
        {
            get
            {            
				IRepository<OutboundMessageQueue> repo = RingCast.OutboundMessageQueue.GetRepo();
				Expression<Func<OutboundMessageQueue, bool>> expression = x => x.MessageId == Id;
				CachedDataLoader<OutboundMessageQueue>.DataRequest dataRequest 
				= new CachedDataLoader<OutboundMessageQueue>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "OutboundMessageQueue", repo, expression);

				return CachedDataLoader<OutboundMessageQueue>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _OutboundMessageQueues = value;
               
               OnChanged();
            }
        }
		
		
		public Customer Customer
		{
			get
			{
				return _Customers.SingleOrDefault(x => x.Id == _CustomerId);
			}								
			set
			{
				CustomerId = value.Id;
			}
		}

		public MessageDirection Direction
		{
			get
			{
				return (MessageDirection)MessageDirectionId;
			}								
			set
			{
				MessageDirectionId = (int)value;
			}
		}

		public Gateway Gateway
		{
			get
			{
				return _Gateways.SingleOrDefault(x => x.Id == _GatewayId);
			}								
			set
			{
				GatewayId = value.Id;
			}
		}

		public Pipe Pipe
		{
			get
			{
				return _Pipes.SingleOrDefault(x => x.Id == _PipeId);
			}								
			set
			{
				PipeId = value.Id;
			}
		}

		public RequestLog RequestLog
		{
			get
			{
				return _RequestLogs.SingleOrDefault(x => x.Id == _RequestLogId);
			}								
			set
			{
				RequestLogId = value.Id;
			}
		}

		public Session Session
		{
			get
			{
				return _Sessions.SingleOrDefault(x => x.Id == _SessionId);
			}								
			set
			{
				SessionId = value.Id;
			}
		}

		public MessageStatus Status
		{
			get
			{
				return (MessageStatus)MessageStatusId;
			}								
			set
			{
				MessageStatusId = (int)value;
			}
		}

		public MessageType Type
		{
			get
			{
				return (MessageType)MessageTypeId;
			}								
			set
			{
				MessageTypeId = (int)value;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _SessionId;
		 [XmlIgnore] 
        public int SessionId
        {
            get { return _SessionId; }
            set
            {
                if(_SessionId!=value){
                    _SessionId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SessionId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _SequenceNumber;
		  
        public int SequenceNumber
        {
            get { return _SequenceNumber; }
            set
            {
                if(_SequenceNumber!=value){
                    _SequenceNumber=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SequenceNumber");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ClientReference;
		  
        public string ClientReference
        {
            get { return _ClientReference; }
            set
            {
                if(_ClientReference!=value){
                    _ClientReference=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ClientReference");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Body;
		  
        public string Body
        {
            get { return _Body; }
            set
            {
                if(_Body!=value){
                    _Body=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Body");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MessageTypeId;
		  
        public int MessageTypeId
        {
            get { return _MessageTypeId; }
            set
            {
                if(_MessageTypeId!=value){
                    _MessageTypeId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MessageTypeId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MessageDirectionId;
		  
        public int MessageDirectionId
        {
            get { return _MessageDirectionId; }
            set
            {
                if(_MessageDirectionId!=value){
                    _MessageDirectionId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MessageDirectionId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MessageStatusId;
		  
        public int MessageStatusId
        {
            get { return _MessageStatusId; }
            set
            {
                if(_MessageStatusId!=value){
                    _MessageStatusId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MessageStatusId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _GatewayId;
		 [XmlIgnore] 
        public int GatewayId
        {
            get { return _GatewayId; }
            set
            {
                if(_GatewayId!=value){
                    _GatewayId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="GatewayId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _CustomerId;
		 [XmlIgnore] 
        public int CustomerId
        {
            get { return _CustomerId; }
            set
            {
                if(_CustomerId!=value){
                    _CustomerId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CustomerId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _PipeId;
		 [XmlIgnore] 
        public int PipeId
        {
            get { return _PipeId; }
            set
            {
                if(_PipeId!=value){
                    _PipeId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="PipeId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _SenderName;
		  
        public string SenderName
        {
            get { return _SenderName; }
            set
            {
                if(_SenderName!=value){
                    _SenderName=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SenderName");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _RequestLogId;
		 [XmlIgnore] 
        public int RequestLogId
        {
            get { return _RequestLogId; }
            set
            {
                if(_RequestLogId!=value){
                    _RequestLogId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="RequestLogId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Attachments != null && Attachments.Count > 0)
				Attachments.ForEach(x => x.Save(provider));	
				
			
			if (Histories != null && Histories.Count > 0)
				Histories.ForEach(x => x.Save(provider));	
				
			
			if (InboundMessageQueues != null && InboundMessageQueues.Count > 0)
				InboundMessageQueues.ForEach(x => x.Save(provider));	
				
			
			if (OutboundBatchMessages != null && OutboundBatchMessages.Count > 0)
				OutboundBatchMessages.ForEach(x => x.Save(provider));	
				
			
			if (OutboundMessageQueues != null && OutboundMessageQueues.Count > 0)
				OutboundMessageQueues.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Attachments != null && Attachments.Count > 0)
				Attachments.ForEach(x => x.Save(username, provider));
				
			
			if (Histories != null && Histories.Count > 0)
				Histories.ForEach(x => x.Save(username, provider));
				
			
			if (InboundMessageQueues != null && InboundMessageQueues.Count > 0)
				InboundMessageQueues.ForEach(x => x.Save(username, provider));
				
			
			if (OutboundBatchMessages != null && OutboundBatchMessages.Count > 0)
				OutboundBatchMessages.ForEach(x => x.Save(username, provider));
				
			
			if (OutboundMessageQueues != null && OutboundMessageQueues.Count > 0)
				OutboundMessageQueues.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            Message item = new Message(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(Message message){
			
			if (message != null)
			{
				try 
				{
					
					this.Id = message.Id;
					
										
					this.SessionId = message.SessionId;
					
										
					this.SequenceNumber = message.SequenceNumber;
					
										
					this.ClientReference = message.ClientReference;
					
										
					this.Body = message.Body;
					
										
					this.MessageTypeId = message.MessageTypeId;
					
										
					this.MessageDirectionId = message.MessageDirectionId;
					
										
					this.MessageStatusId = message.MessageStatusId;
					
										
					this.GatewayId = message.GatewayId;
					
										
					this.CustomerId = message.CustomerId;
					
										
					this.PipeId = message.PipeId;
					
										
					this.SenderName = message.SenderName;
					
										
					this.RequestLogId = message.RequestLogId;
					
										
					this.CreatedOn = message.CreatedOn;
					
										
					this.CreatedBy = message.CreatedBy;
					
										
					this.ModifiedOn = message.ModifiedOn;
					
										
					this.ModifiedBy = message.ModifiedBy;
					
										
					this.IsDeleted = message.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public Message(Message message):this() {

			Load(message);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<Message, bool>> expression) {
            var repo = GetRepo();
            
            
            List<Message> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<Message, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the Countries table in the RingCast Database.
    /// </summary>
    public partial class Country: BusinessObject<Country>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<Country>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<Country> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<Country>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<Country> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(Country item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                Country item=new Country();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<Country> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public Country(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                Country.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Country>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public Country(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public Country(Expression<Func<Country, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<Country> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<Country> _repo;
            
            if(db.TestMode){
                Country.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Country>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<Country> GetRepo(){
            return GetRepo("","");
        }
        
        public static Country SingleOrDefault(Expression<Func<Country, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            Country single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static Country SingleOrDefault(Expression<Func<Country, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            Country single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<Country, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<Country, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<Country> Find(Expression<Func<Country, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<Country> Find(Expression<Func<Country, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<Country> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<Country> All() {
            return GetRepo().GetAll();
        }

		public static List<Country> FetchAll(string connectionString, string providerName) 
		{
            IRepository<Country> repo = RingCast.Country.GetRepo(connectionString,providerName);
			CachedDataLoader<Country>.DataRequest dataRequest 
			= new CachedDataLoader<Country>.DataRequest("RingCast", connectionString, "Countries", repo);

			return CachedDataLoader<Country>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<Country> FetchAll(Expression<Func<Country, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<Country> repo = RingCast.Country.GetRepo();
			CachedDataLoader<Country>.DataRequest dataRequest 
			= new CachedDataLoader<Country>.DataRequest("RingCast", db.DataProvider.ConnectionString, "Countries", repo, expression);

			return CachedDataLoader<Country>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<Country> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<Country> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<Country> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<Country> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<Country> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(Country)){
                Country compare=(Country)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<NetworkOperator> _NetworkOperators;
		public List<NetworkOperator> NetworkOperators
        {
            get
            {            
				IRepository<NetworkOperator> repo = RingCast.NetworkOperator.GetRepo();
				Expression<Func<NetworkOperator, bool>> expression = x => x.CountryId == Id;
				CachedDataLoader<NetworkOperator>.DataRequest dataRequest 
				= new CachedDataLoader<NetworkOperator>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "NetworkOperators", repo, expression);

				return CachedDataLoader<NetworkOperator>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _NetworkOperators = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<OutboundGatewayCountry> _OutboundGatewayCountries;
		public List<OutboundGatewayCountry> OutboundGatewayCountries
        {
            get
            {            
				IRepository<OutboundGatewayCountry> repo = RingCast.OutboundGatewayCountry.GetRepo();
				Expression<Func<OutboundGatewayCountry, bool>> expression = x => x.CountryId == Id;
				CachedDataLoader<OutboundGatewayCountry>.DataRequest dataRequest 
				= new CachedDataLoader<OutboundGatewayCountry>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "OutboundGatewayCountries", repo, expression);

				return CachedDataLoader<OutboundGatewayCountry>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _OutboundGatewayCountries = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<Pipe> _Pipes;
		public List<Pipe> Pipes
        {
            get
            {            
				IRepository<Pipe> repo = RingCast.Pipe.GetRepo();
				Expression<Func<Pipe, bool>> expression = x => x.CountryId == Id;
				CachedDataLoader<Pipe>.DataRequest dataRequest 
				= new CachedDataLoader<Pipe>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Pipes", repo, expression);

				return CachedDataLoader<Pipe>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Pipes = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Code;
		  
        public string Code
        {
            get { return _Code; }
            set
            {
                if(_Code!=value){
                    _Code=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Code");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _Prefix;
		  
        public int Prefix
        {
            get { return _Prefix; }
            set
            {
                if(_Prefix!=value){
                    _Prefix=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Prefix");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MCC;
		  
        public int MCC
        {
            get { return _MCC; }
            set
            {
                if(_MCC!=value){
                    _MCC=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MCC");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Currency;
		  
        public string Currency
        {
            get { return _Currency; }
            set
            {
                if(_Currency!=value){
                    _Currency=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Currency");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CurrencySymbol;
		  
        public string CurrencySymbol
        {
            get { return _CurrencySymbol; }
            set
            {
                if(_CurrencySymbol!=value){
                    _CurrencySymbol=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CurrencySymbol");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (NetworkOperators != null && NetworkOperators.Count > 0)
				NetworkOperators.ForEach(x => x.Save(provider));	
				
			
			if (OutboundGatewayCountries != null && OutboundGatewayCountries.Count > 0)
				OutboundGatewayCountries.ForEach(x => x.Save(provider));	
				
			
			if (Pipes != null && Pipes.Count > 0)
				Pipes.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (NetworkOperators != null && NetworkOperators.Count > 0)
				NetworkOperators.ForEach(x => x.Save(username, provider));
				
			
			if (OutboundGatewayCountries != null && OutboundGatewayCountries.Count > 0)
				OutboundGatewayCountries.ForEach(x => x.Save(username, provider));
				
			
			if (Pipes != null && Pipes.Count > 0)
				Pipes.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            Country item = new Country(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(Country country){
			
			if (country != null)
			{
				try 
				{
					
					this.Id = country.Id;
					
										
					this.Name = country.Name;
					
										
					this.Code = country.Code;
					
										
					this.Prefix = country.Prefix;
					
										
					this.MCC = country.MCC;
					
										
					this.Currency = country.Currency;
					
										
					this.CurrencySymbol = country.CurrencySymbol;
					
										
					this.CreatedOn = country.CreatedOn;
					
										
					this.CreatedBy = country.CreatedBy;
					
										
					this.ModifiedOn = country.ModifiedOn;
					
										
					this.ModifiedBy = country.ModifiedBy;
					
										
					this.IsDeleted = country.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public Country(Country country):this() {

			Load(country);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<Country, bool>> expression) {
            var repo = GetRepo();
            
            
            List<Country> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<Country, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the PipeMappings table in the RingCast Database.
    /// </summary>
    public partial class PipeMapping: BusinessObject<PipeMapping>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<PipeMapping>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<PipeMapping> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<PipeMapping>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<PipeMapping> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(PipeMapping item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                PipeMapping item=new PipeMapping();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<PipeMapping> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public PipeMapping(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                PipeMapping.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<PipeMapping>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public PipeMapping(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public PipeMapping(Expression<Func<PipeMapping, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<PipeMapping> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<PipeMapping> _repo;
            
            if(db.TestMode){
                PipeMapping.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<PipeMapping>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<PipeMapping> GetRepo(){
            return GetRepo("","");
        }
        
        public static PipeMapping SingleOrDefault(Expression<Func<PipeMapping, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            PipeMapping single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static PipeMapping SingleOrDefault(Expression<Func<PipeMapping, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            PipeMapping single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<PipeMapping, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<PipeMapping, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<PipeMapping> Find(Expression<Func<PipeMapping, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<PipeMapping> Find(Expression<Func<PipeMapping, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<PipeMapping> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<PipeMapping> All() {
            return GetRepo().GetAll();
        }

		public static List<PipeMapping> FetchAll(string connectionString, string providerName) 
		{
            IRepository<PipeMapping> repo = RingCast.PipeMapping.GetRepo(connectionString,providerName);
			CachedDataLoader<PipeMapping>.DataRequest dataRequest 
			= new CachedDataLoader<PipeMapping>.DataRequest("RingCast", connectionString, "PipeMappings", repo);

			return CachedDataLoader<PipeMapping>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<PipeMapping> FetchAll(Expression<Func<PipeMapping, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<PipeMapping> repo = RingCast.PipeMapping.GetRepo();
			CachedDataLoader<PipeMapping>.DataRequest dataRequest 
			= new CachedDataLoader<PipeMapping>.DataRequest("RingCast", db.DataProvider.ConnectionString, "PipeMappings", repo, expression);

			return CachedDataLoader<PipeMapping>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<PipeMapping> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<PipeMapping> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<PipeMapping> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<PipeMapping> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<PipeMapping> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Identifier.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(PipeMapping)){
                PipeMapping compare=(PipeMapping)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Identifier.ToString();
        }

        public string DescriptorColumn() {
            return "Identifier";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Identifier";
        }
        
        #region ' Foreign Keys '
		private List<NetworkOperator> _NetworkOperators
        {
            get
            {            
				IRepository<NetworkOperator> repo = RingCast.NetworkOperator.GetRepo();
				Expression<Func<NetworkOperator, bool>> expression = x => x.Id == NetworkOperatorId;
				CachedDataLoader<NetworkOperator>.DataRequest dataRequest 
				= new CachedDataLoader<NetworkOperator>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "NetworkOperators", repo, expression);

				return CachedDataLoader<NetworkOperator>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<Pipe> _Pipes
        {
            get
            {            
				IRepository<Pipe> repo = RingCast.Pipe.GetRepo();
				Expression<Func<Pipe, bool>> expression = x => x.Id == PipeId;
				CachedDataLoader<Pipe>.DataRequest dataRequest 
				= new CachedDataLoader<Pipe>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Pipes", repo, expression);

				return CachedDataLoader<Pipe>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public NetworkOperator NetworkOperator
		{
			get
			{
				return _NetworkOperators.SingleOrDefault(x => x.Id == _NetworkOperatorId);
			}								
			set
			{
				NetworkOperatorId = value.Id;
			}
		}

		public Pipe Pipe
		{
			get
			{
				return _Pipes.SingleOrDefault(x => x.Id == _PipeId);
			}								
			set
			{
				PipeId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _PipeId;
		 [XmlIgnore] 
        public int PipeId
        {
            get { return _PipeId; }
            set
            {
                if(_PipeId!=value){
                    _PipeId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="PipeId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Identifier;
		  
        public string Identifier
        {
            get { return _Identifier; }
            set
            {
                if(_Identifier!=value){
                    _Identifier=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Identifier");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _NetworkOperatorId;
		 [XmlIgnore] 
        public int NetworkOperatorId
        {
            get { return _NetworkOperatorId; }
            set
            {
                if(_NetworkOperatorId!=value){
                    _NetworkOperatorId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NetworkOperatorId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _BindIdentifier;
		  
        public string BindIdentifier
        {
            get { return _BindIdentifier; }
            set
            {
                if(_BindIdentifier!=value){
                    _BindIdentifier=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="BindIdentifier");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            PipeMapping item = new PipeMapping(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(PipeMapping pipeMapping){
			
			if (pipeMapping != null)
			{
				try 
				{
					
					this.Id = pipeMapping.Id;
					
										
					this.PipeId = pipeMapping.PipeId;
					
										
					this.Identifier = pipeMapping.Identifier;
					
										
					this.NetworkOperatorId = pipeMapping.NetworkOperatorId;
					
										
					this.BindIdentifier = pipeMapping.BindIdentifier;
					
										
					this.CreatedOn = pipeMapping.CreatedOn;
					
										
					this.CreatedBy = pipeMapping.CreatedBy;
					
										
					this.ModifiedOn = pipeMapping.ModifiedOn;
					
										
					this.ModifiedBy = pipeMapping.ModifiedBy;
					
										
					this.IsDeleted = pipeMapping.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public PipeMapping(PipeMapping pipeMapping):this() {

			Load(pipeMapping);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<PipeMapping, bool>> expression) {
            var repo = GetRepo();
            
            
            List<PipeMapping> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<PipeMapping, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the OutboundGatewayCountries table in the RingCast Database.
    /// </summary>
    public partial class OutboundGatewayCountry: BusinessObject<OutboundGatewayCountry>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<OutboundGatewayCountry>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<OutboundGatewayCountry> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<OutboundGatewayCountry>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<OutboundGatewayCountry> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(OutboundGatewayCountry item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                OutboundGatewayCountry item=new OutboundGatewayCountry();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<OutboundGatewayCountry> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public OutboundGatewayCountry(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                OutboundGatewayCountry.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<OutboundGatewayCountry>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public OutboundGatewayCountry(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public OutboundGatewayCountry(Expression<Func<OutboundGatewayCountry, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<OutboundGatewayCountry> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<OutboundGatewayCountry> _repo;
            
            if(db.TestMode){
                OutboundGatewayCountry.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<OutboundGatewayCountry>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<OutboundGatewayCountry> GetRepo(){
            return GetRepo("","");
        }
        
        public static OutboundGatewayCountry SingleOrDefault(Expression<Func<OutboundGatewayCountry, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            OutboundGatewayCountry single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static OutboundGatewayCountry SingleOrDefault(Expression<Func<OutboundGatewayCountry, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            OutboundGatewayCountry single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<OutboundGatewayCountry, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<OutboundGatewayCountry, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<OutboundGatewayCountry> Find(Expression<Func<OutboundGatewayCountry, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<OutboundGatewayCountry> Find(Expression<Func<OutboundGatewayCountry, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<OutboundGatewayCountry> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<OutboundGatewayCountry> All() {
            return GetRepo().GetAll();
        }

		public static List<OutboundGatewayCountry> FetchAll(string connectionString, string providerName) 
		{
            IRepository<OutboundGatewayCountry> repo = RingCast.OutboundGatewayCountry.GetRepo(connectionString,providerName);
			CachedDataLoader<OutboundGatewayCountry>.DataRequest dataRequest 
			= new CachedDataLoader<OutboundGatewayCountry>.DataRequest("RingCast", connectionString, "OutboundGatewayCountries", repo);

			return CachedDataLoader<OutboundGatewayCountry>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<OutboundGatewayCountry> FetchAll(Expression<Func<OutboundGatewayCountry, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<OutboundGatewayCountry> repo = RingCast.OutboundGatewayCountry.GetRepo();
			CachedDataLoader<OutboundGatewayCountry>.DataRequest dataRequest 
			= new CachedDataLoader<OutboundGatewayCountry>.DataRequest("RingCast", db.DataProvider.ConnectionString, "OutboundGatewayCountries", repo, expression);

			return CachedDataLoader<OutboundGatewayCountry>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<OutboundGatewayCountry> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<OutboundGatewayCountry> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<OutboundGatewayCountry> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<OutboundGatewayCountry> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<OutboundGatewayCountry> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.CreatedBy.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(OutboundGatewayCountry)){
                OutboundGatewayCountry compare=(OutboundGatewayCountry)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.CreatedBy.ToString();
        }

        public string DescriptorColumn() {
            return "CreatedBy";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "CreatedBy";
        }
        
        #region ' Foreign Keys '
		private List<Country> _Countries
        {
            get
            {            
				IRepository<Country> repo = RingCast.Country.GetRepo();
				Expression<Func<Country, bool>> expression = x => x.Id == CountryId;
				CachedDataLoader<Country>.DataRequest dataRequest 
				= new CachedDataLoader<Country>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Countries", repo, expression);

				return CachedDataLoader<Country>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<Gateway> _Gateways
        {
            get
            {            
				IRepository<Gateway> repo = RingCast.Gateway.GetRepo();
				Expression<Func<Gateway, bool>> expression = x => x.Id == GatewayId;
				CachedDataLoader<Gateway>.DataRequest dataRequest 
				= new CachedDataLoader<Gateway>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Gateways", repo, expression);

				return CachedDataLoader<Gateway>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Country Country
		{
			get
			{
				return _Countries.SingleOrDefault(x => x.Id == _CountryId);
			}								
			set
			{
				CountryId = value.Id;
			}
		}

		public Gateway Gateway
		{
			get
			{
				return _Gateways.SingleOrDefault(x => x.Id == _GatewayId);
			}								
			set
			{
				GatewayId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _CountryId;
		 [XmlIgnore] 
        public int CountryId
        {
            get { return _CountryId; }
            set
            {
                if(_CountryId!=value){
                    _CountryId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CountryId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _GatewayId;
		 [XmlIgnore] 
        public int GatewayId
        {
            get { return _GatewayId; }
            set
            {
                if(_GatewayId!=value){
                    _GatewayId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="GatewayId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            OutboundGatewayCountry item = new OutboundGatewayCountry(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(OutboundGatewayCountry outboundGatewayCountry){
			
			if (outboundGatewayCountry != null)
			{
				try 
				{
					
					this.Id = outboundGatewayCountry.Id;
					
										
					this.CountryId = outboundGatewayCountry.CountryId;
					
										
					this.GatewayId = outboundGatewayCountry.GatewayId;
					
										
					this.CreatedOn = outboundGatewayCountry.CreatedOn;
					
										
					this.CreatedBy = outboundGatewayCountry.CreatedBy;
					
										
					this.ModifiedOn = outboundGatewayCountry.ModifiedOn;
					
										
					this.ModifiedBy = outboundGatewayCountry.ModifiedBy;
					
										
					this.IsDeleted = outboundGatewayCountry.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public OutboundGatewayCountry(OutboundGatewayCountry outboundGatewayCountry):this() {

			Load(outboundGatewayCountry);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<OutboundGatewayCountry, bool>> expression) {
            var repo = GetRepo();
            
            
            List<OutboundGatewayCountry> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<OutboundGatewayCountry, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the InboundMessageQueue table in the RingCast Database.
    /// </summary>
    public partial class InboundMessageQueue: BusinessObject<InboundMessageQueue>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<InboundMessageQueue>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<InboundMessageQueue> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<InboundMessageQueue>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<InboundMessageQueue> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(InboundMessageQueue item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                InboundMessageQueue item=new InboundMessageQueue();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<InboundMessageQueue> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public InboundMessageQueue(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                InboundMessageQueue.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<InboundMessageQueue>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public InboundMessageQueue(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public InboundMessageQueue(Expression<Func<InboundMessageQueue, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<InboundMessageQueue> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<InboundMessageQueue> _repo;
            
            if(db.TestMode){
                InboundMessageQueue.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<InboundMessageQueue>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<InboundMessageQueue> GetRepo(){
            return GetRepo("","");
        }
        
        public static InboundMessageQueue SingleOrDefault(Expression<Func<InboundMessageQueue, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            InboundMessageQueue single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static InboundMessageQueue SingleOrDefault(Expression<Func<InboundMessageQueue, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            InboundMessageQueue single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<InboundMessageQueue, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<InboundMessageQueue, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<InboundMessageQueue> Find(Expression<Func<InboundMessageQueue, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<InboundMessageQueue> Find(Expression<Func<InboundMessageQueue, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<InboundMessageQueue> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<InboundMessageQueue> All() {
            return GetRepo().GetAll();
        }

		public static List<InboundMessageQueue> FetchAll(string connectionString, string providerName) 
		{
            IRepository<InboundMessageQueue> repo = RingCast.InboundMessageQueue.GetRepo(connectionString,providerName);
			CachedDataLoader<InboundMessageQueue>.DataRequest dataRequest 
			= new CachedDataLoader<InboundMessageQueue>.DataRequest("RingCast", connectionString, "InboundMessageQueue", repo);

			return CachedDataLoader<InboundMessageQueue>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<InboundMessageQueue> FetchAll(Expression<Func<InboundMessageQueue, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<InboundMessageQueue> repo = RingCast.InboundMessageQueue.GetRepo();
			CachedDataLoader<InboundMessageQueue>.DataRequest dataRequest 
			= new CachedDataLoader<InboundMessageQueue>.DataRequest("RingCast", db.DataProvider.ConnectionString, "InboundMessageQueue", repo, expression);

			return CachedDataLoader<InboundMessageQueue>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<InboundMessageQueue> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<InboundMessageQueue> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<InboundMessageQueue> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<InboundMessageQueue> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<InboundMessageQueue> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.CreatedBy.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(InboundMessageQueue)){
                InboundMessageQueue compare=(InboundMessageQueue)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.CreatedBy.ToString();
        }

        public string DescriptorColumn() {
            return "CreatedBy";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "CreatedBy";
        }
        
        #region ' Foreign Keys '
		private List<Message> _Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.Id == MessageId;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Message Message
		{
			get
			{
				return _Messages.SingleOrDefault(x => x.Id == _MessageId);
			}								
			set
			{
				MessageId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MessageId;
		 [XmlIgnore] 
        public int MessageId
        {
            get { return _MessageId; }
            set
            {
                if(_MessageId!=value){
                    _MessageId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MessageId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
       
            
            repo.Delete(key);
            
        }
        
        protected void Load(InboundMessageQueue inboundMessageQueue){
			
			if (inboundMessageQueue != null)
			{
				try 
				{
					
					this.Id = inboundMessageQueue.Id;
					
										
					this.MessageId = inboundMessageQueue.MessageId;
					
										
					this.CreatedOn = inboundMessageQueue.CreatedOn;
					
										
					this.CreatedBy = inboundMessageQueue.CreatedBy;
					
										
					this.ModifiedOn = inboundMessageQueue.ModifiedOn;
					
										
					this.ModifiedBy = inboundMessageQueue.ModifiedBy;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public InboundMessageQueue(InboundMessageQueue inboundMessageQueue):this() {

			Load(inboundMessageQueue);
        }   
        

        public void Delete(IDataProvider provider) {
                   
                 
            _repo.Delete(KeyValue());
            
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<InboundMessageQueue, bool>> expression) {
            var repo = GetRepo();
            
       
            
            return repo.DeleteMany(expression);
            
        }

        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the NetworkOperators table in the RingCast Database.
    /// </summary>
    public partial class NetworkOperator: BusinessObject<NetworkOperator>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<NetworkOperator>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<NetworkOperator> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<NetworkOperator>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<NetworkOperator> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(NetworkOperator item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                NetworkOperator item=new NetworkOperator();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<NetworkOperator> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public NetworkOperator(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                NetworkOperator.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<NetworkOperator>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public NetworkOperator(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public NetworkOperator(Expression<Func<NetworkOperator, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<NetworkOperator> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<NetworkOperator> _repo;
            
            if(db.TestMode){
                NetworkOperator.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<NetworkOperator>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<NetworkOperator> GetRepo(){
            return GetRepo("","");
        }
        
        public static NetworkOperator SingleOrDefault(Expression<Func<NetworkOperator, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            NetworkOperator single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static NetworkOperator SingleOrDefault(Expression<Func<NetworkOperator, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            NetworkOperator single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<NetworkOperator, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<NetworkOperator, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<NetworkOperator> Find(Expression<Func<NetworkOperator, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<NetworkOperator> Find(Expression<Func<NetworkOperator, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<NetworkOperator> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<NetworkOperator> All() {
            return GetRepo().GetAll();
        }

		public static List<NetworkOperator> FetchAll(string connectionString, string providerName) 
		{
            IRepository<NetworkOperator> repo = RingCast.NetworkOperator.GetRepo(connectionString,providerName);
			CachedDataLoader<NetworkOperator>.DataRequest dataRequest 
			= new CachedDataLoader<NetworkOperator>.DataRequest("RingCast", connectionString, "NetworkOperators", repo);

			return CachedDataLoader<NetworkOperator>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<NetworkOperator> FetchAll(Expression<Func<NetworkOperator, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<NetworkOperator> repo = RingCast.NetworkOperator.GetRepo();
			CachedDataLoader<NetworkOperator>.DataRequest dataRequest 
			= new CachedDataLoader<NetworkOperator>.DataRequest("RingCast", db.DataProvider.ConnectionString, "NetworkOperators", repo, expression);

			return CachedDataLoader<NetworkOperator>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<NetworkOperator> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<NetworkOperator> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<NetworkOperator> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<NetworkOperator> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<NetworkOperator> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(NetworkOperator)){
                NetworkOperator compare=(NetworkOperator)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		private List<Country> _Countries
        {
            get
            {            
				IRepository<Country> repo = RingCast.Country.GetRepo();
				Expression<Func<Country, bool>> expression = x => x.Id == CountryId;
				CachedDataLoader<Country>.DataRequest dataRequest 
				= new CachedDataLoader<Country>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Countries", repo, expression);

				return CachedDataLoader<Country>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		
		private List<Customer> _Customers;
		public List<Customer> Customers
        {
            get
            {            
				IRepository<Customer> repo = RingCast.Customer.GetRepo();
				Expression<Func<Customer, bool>> expression = x => x.NetworkOperatorId == Id;
				CachedDataLoader<Customer>.DataRequest dataRequest 
				= new CachedDataLoader<Customer>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Customers", repo, expression);

				return CachedDataLoader<Customer>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Customers = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<PipeMapping> _PipeMappings;
		public List<PipeMapping> PipeMappings
        {
            get
            {            
				IRepository<PipeMapping> repo = RingCast.PipeMapping.GetRepo();
				Expression<Func<PipeMapping, bool>> expression = x => x.NetworkOperatorId == Id;
				CachedDataLoader<PipeMapping>.DataRequest dataRequest 
				= new CachedDataLoader<PipeMapping>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "PipeMappings", repo, expression);

				return CachedDataLoader<PipeMapping>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _PipeMappings = value;
               
               OnChanged();
            }
        }
		
		
		public Country Country
		{
			get
			{
				return _Countries.SingleOrDefault(x => x.Id == _CountryId);
			}								
			set
			{
				CountryId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MNC;
		  
        public int MNC
        {
            get { return _MNC; }
            set
            {
                if(_MNC!=value){
                    _MNC=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MNC");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _CountryId;
		 [XmlIgnore] 
        public int CountryId
        {
            get { return _CountryId; }
            set
            {
                if(_CountryId!=value){
                    _CountryId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CountryId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Customers != null && Customers.Count > 0)
				Customers.ForEach(x => x.Save(provider));	
				
			
			if (PipeMappings != null && PipeMappings.Count > 0)
				PipeMappings.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Customers != null && Customers.Count > 0)
				Customers.ForEach(x => x.Save(username, provider));
				
			
			if (PipeMappings != null && PipeMappings.Count > 0)
				PipeMappings.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            NetworkOperator item = new NetworkOperator(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(NetworkOperator networkOperator){
			
			if (networkOperator != null)
			{
				try 
				{
					
					this.Id = networkOperator.Id;
					
										
					this.Name = networkOperator.Name;
					
										
					this.MNC = networkOperator.MNC;
					
										
					this.CountryId = networkOperator.CountryId;
					
										
					this.CreatedOn = networkOperator.CreatedOn;
					
										
					this.CreatedBy = networkOperator.CreatedBy;
					
										
					this.ModifiedOn = networkOperator.ModifiedOn;
					
										
					this.ModifiedBy = networkOperator.ModifiedBy;
					
										
					this.IsDeleted = networkOperator.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public NetworkOperator(NetworkOperator networkOperator):this() {

			Load(networkOperator);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<NetworkOperator, bool>> expression) {
            var repo = GetRepo();
            
            
            List<NetworkOperator> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<NetworkOperator, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the OutboundMessageQueue table in the RingCast Database.
    /// </summary>
    public partial class OutboundMessageQueue: BusinessObject<OutboundMessageQueue>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<OutboundMessageQueue>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<OutboundMessageQueue> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<OutboundMessageQueue>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<OutboundMessageQueue> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(OutboundMessageQueue item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                OutboundMessageQueue item=new OutboundMessageQueue();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<OutboundMessageQueue> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public OutboundMessageQueue(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                OutboundMessageQueue.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<OutboundMessageQueue>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public OutboundMessageQueue(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public OutboundMessageQueue(Expression<Func<OutboundMessageQueue, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<OutboundMessageQueue> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<OutboundMessageQueue> _repo;
            
            if(db.TestMode){
                OutboundMessageQueue.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<OutboundMessageQueue>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<OutboundMessageQueue> GetRepo(){
            return GetRepo("","");
        }
        
        public static OutboundMessageQueue SingleOrDefault(Expression<Func<OutboundMessageQueue, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            OutboundMessageQueue single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static OutboundMessageQueue SingleOrDefault(Expression<Func<OutboundMessageQueue, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            OutboundMessageQueue single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<OutboundMessageQueue, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<OutboundMessageQueue, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<OutboundMessageQueue> Find(Expression<Func<OutboundMessageQueue, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<OutboundMessageQueue> Find(Expression<Func<OutboundMessageQueue, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<OutboundMessageQueue> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<OutboundMessageQueue> All() {
            return GetRepo().GetAll();
        }

		public static List<OutboundMessageQueue> FetchAll(string connectionString, string providerName) 
		{
            IRepository<OutboundMessageQueue> repo = RingCast.OutboundMessageQueue.GetRepo(connectionString,providerName);
			CachedDataLoader<OutboundMessageQueue>.DataRequest dataRequest 
			= new CachedDataLoader<OutboundMessageQueue>.DataRequest("RingCast", connectionString, "OutboundMessageQueue", repo);

			return CachedDataLoader<OutboundMessageQueue>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<OutboundMessageQueue> FetchAll(Expression<Func<OutboundMessageQueue, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<OutboundMessageQueue> repo = RingCast.OutboundMessageQueue.GetRepo();
			CachedDataLoader<OutboundMessageQueue>.DataRequest dataRequest 
			= new CachedDataLoader<OutboundMessageQueue>.DataRequest("RingCast", db.DataProvider.ConnectionString, "OutboundMessageQueue", repo, expression);

			return CachedDataLoader<OutboundMessageQueue>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<OutboundMessageQueue> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<OutboundMessageQueue> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<OutboundMessageQueue> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<OutboundMessageQueue> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<OutboundMessageQueue> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.CreatedBy.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(OutboundMessageQueue)){
                OutboundMessageQueue compare=(OutboundMessageQueue)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.CreatedBy.ToString();
        }

        public string DescriptorColumn() {
            return "CreatedBy";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "CreatedBy";
        }
        
        #region ' Foreign Keys '
		private List<Message> _Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.Id == MessageId;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Message Message
		{
			get
			{
				return _Messages.SingleOrDefault(x => x.Id == _MessageId);
			}								
			set
			{
				MessageId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MessageId;
		 [XmlIgnore] 
        public int MessageId
        {
            get { return _MessageId; }
            set
            {
                if(_MessageId!=value){
                    _MessageId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MessageId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
       
            
            repo.Delete(key);
            
        }
        
        protected void Load(OutboundMessageQueue outboundMessageQueue){
			
			if (outboundMessageQueue != null)
			{
				try 
				{
					
					this.Id = outboundMessageQueue.Id;
					
										
					this.MessageId = outboundMessageQueue.MessageId;
					
										
					this.CreatedOn = outboundMessageQueue.CreatedOn;
					
										
					this.CreatedBy = outboundMessageQueue.CreatedBy;
					
										
					this.ModifiedOn = outboundMessageQueue.ModifiedOn;
					
										
					this.ModifiedBy = outboundMessageQueue.ModifiedBy;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public OutboundMessageQueue(OutboundMessageQueue outboundMessageQueue):this() {

			Load(outboundMessageQueue);
        }   
        

        public void Delete(IDataProvider provider) {
                   
                 
            _repo.Delete(KeyValue());
            
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<OutboundMessageQueue, bool>> expression) {
            var repo = GetRepo();
            
       
            
            return repo.DeleteMany(expression);
            
        }

        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the Customers table in the RingCast Database.
    /// </summary>
    public partial class Customer: BusinessObject<Customer>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<Customer>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<Customer> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<Customer>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<Customer> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(Customer item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                Customer item=new Customer();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<Customer> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public Customer(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                Customer.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Customer>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public Customer(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public Customer(Expression<Func<Customer, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<Customer> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<Customer> _repo;
            
            if(db.TestMode){
                Customer.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Customer>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<Customer> GetRepo(){
            return GetRepo("","");
        }
        
        public static Customer SingleOrDefault(Expression<Func<Customer, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            Customer single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static Customer SingleOrDefault(Expression<Func<Customer, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            Customer single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<Customer, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<Customer, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<Customer> Find(Expression<Func<Customer, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<Customer> Find(Expression<Func<Customer, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<Customer> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<Customer> All() {
            return GetRepo().GetAll();
        }

		public static List<Customer> FetchAll(string connectionString, string providerName) 
		{
            IRepository<Customer> repo = RingCast.Customer.GetRepo(connectionString,providerName);
			CachedDataLoader<Customer>.DataRequest dataRequest 
			= new CachedDataLoader<Customer>.DataRequest("RingCast", connectionString, "Customers", repo);

			return CachedDataLoader<Customer>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<Customer> FetchAll(Expression<Func<Customer, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<Customer> repo = RingCast.Customer.GetRepo();
			CachedDataLoader<Customer>.DataRequest dataRequest 
			= new CachedDataLoader<Customer>.DataRequest("RingCast", db.DataProvider.ConnectionString, "Customers", repo, expression);

			return CachedDataLoader<Customer>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<Customer> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<Customer> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<Customer> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<Customer> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<Customer> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Identifier.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(Customer)){
                Customer compare=(Customer)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Identifier.ToString();
        }

        public string DescriptorColumn() {
            return "Identifier";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Identifier";
        }
        
        #region ' Foreign Keys '
		private List<NetworkOperator> _NetworkOperators
        {
            get
            {            
				IRepository<NetworkOperator> repo = RingCast.NetworkOperator.GetRepo();
				Expression<Func<NetworkOperator, bool>> expression = x => x.Id == NetworkOperatorId;
				CachedDataLoader<NetworkOperator>.DataRequest dataRequest 
				= new CachedDataLoader<NetworkOperator>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "NetworkOperators", repo, expression);

				return CachedDataLoader<NetworkOperator>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		
		private List<Message> _Messages;
		public List<Message> Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.CustomerId == Id;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Messages = value;
               
               OnChanged();
            }
        }
		
		
		public NetworkOperator NetworkOperator
		{
			get
			{
				return _NetworkOperators.SingleOrDefault(x => x.Id == _NetworkOperatorId);
			}								
			set
			{
				NetworkOperatorId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Identifier;
		  
        public string Identifier
        {
            get { return _Identifier; }
            set
            {
                if(_Identifier!=value){
                    _Identifier=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Identifier");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _NetworkOperatorId;
		 [XmlIgnore] 
        public int NetworkOperatorId
        {
            get { return _NetworkOperatorId; }
            set
            {
                if(_NetworkOperatorId!=value){
                    _NetworkOperatorId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="NetworkOperatorId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            Customer item = new Customer(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(Customer customer){
			
			if (customer != null)
			{
				try 
				{
					
					this.Id = customer.Id;
					
										
					this.Identifier = customer.Identifier;
					
										
					this.NetworkOperatorId = customer.NetworkOperatorId;
					
										
					this.CreatedOn = customer.CreatedOn;
					
										
					this.CreatedBy = customer.CreatedBy;
					
										
					this.ModifiedOn = customer.ModifiedOn;
					
										
					this.ModifiedBy = customer.ModifiedBy;
					
										
					this.IsDeleted = customer.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public Customer(Customer customer):this() {

			Load(customer);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<Customer, bool>> expression) {
            var repo = GetRepo();
            
            
            List<Customer> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<Customer, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the ClientUsers table in the RingCast Database.
    /// </summary>
    public partial class ClientUser: BusinessObject<ClientUser>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<ClientUser>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<ClientUser> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<ClientUser>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<ClientUser> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(ClientUser item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                ClientUser item=new ClientUser();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<ClientUser> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public ClientUser(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                ClientUser.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<ClientUser>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public ClientUser(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public ClientUser(Expression<Func<ClientUser, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<ClientUser> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<ClientUser> _repo;
            
            if(db.TestMode){
                ClientUser.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<ClientUser>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<ClientUser> GetRepo(){
            return GetRepo("","");
        }
        
        public static ClientUser SingleOrDefault(Expression<Func<ClientUser, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            ClientUser single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static ClientUser SingleOrDefault(Expression<Func<ClientUser, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            ClientUser single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<ClientUser, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<ClientUser, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<ClientUser> Find(Expression<Func<ClientUser, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<ClientUser> Find(Expression<Func<ClientUser, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<ClientUser> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<ClientUser> All() {
            return GetRepo().GetAll();
        }

		public static List<ClientUser> FetchAll(string connectionString, string providerName) 
		{
            IRepository<ClientUser> repo = RingCast.ClientUser.GetRepo(connectionString,providerName);
			CachedDataLoader<ClientUser>.DataRequest dataRequest 
			= new CachedDataLoader<ClientUser>.DataRequest("RingCast", connectionString, "ClientUsers", repo);

			return CachedDataLoader<ClientUser>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<ClientUser> FetchAll(Expression<Func<ClientUser, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<ClientUser> repo = RingCast.ClientUser.GetRepo();
			CachedDataLoader<ClientUser>.DataRequest dataRequest 
			= new CachedDataLoader<ClientUser>.DataRequest("RingCast", db.DataProvider.ConnectionString, "ClientUsers", repo, expression);

			return CachedDataLoader<ClientUser>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<ClientUser> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<ClientUser> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<ClientUser> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<ClientUser> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<ClientUser> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Position.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(ClientUser)){
                ClientUser compare=(ClientUser)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Position.ToString();
        }

        public string DescriptorColumn() {
            return "Position";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Position";
        }
        
        #region ' Foreign Keys '
		private List<aspnet_User> _aspnet_Users
        {
            get
            {            
				IRepository<aspnet_User> repo = RingCast.aspnet_User.GetRepo();
				Expression<Func<aspnet_User, bool>> expression = x => x.UserId == aspnet_UserId;
				CachedDataLoader<aspnet_User>.DataRequest dataRequest 
				= new CachedDataLoader<aspnet_User>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "aspnet_Users", repo, expression);

				return CachedDataLoader<aspnet_User>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<Client> _Clients
        {
            get
            {            
				IRepository<Client> repo = RingCast.Client.GetRepo();
				Expression<Func<Client, bool>> expression = x => x.Id == ClientId;
				CachedDataLoader<Client>.DataRequest dataRequest 
				= new CachedDataLoader<Client>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Clients", repo, expression);

				return CachedDataLoader<Client>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public aspnet_User aspnet_User
		{
			get
			{
				return _aspnet_Users.SingleOrDefault(x => x.UserId == _aspnet_UserId);
			}								
			set
			{
				aspnet_UserId = value.UserId;
			}
		}

		public Client Client
		{
			get
			{
				return _Clients.SingleOrDefault(x => x.Id == _ClientId);
			}								
			set
			{
				ClientId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _ClientId;
		 [XmlIgnore] 
        public int ClientId
        {
            get { return _ClientId; }
            set
            {
                if(_ClientId!=value){
                    _ClientId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ClientId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        Guid _aspnet_UserId;
		 [XmlIgnore] 
        public Guid aspnet_UserId
        {
            get { return _aspnet_UserId; }
            set
            {
                if(_aspnet_UserId!=value){
                    _aspnet_UserId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="aspnet_UserId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Position;
		  
        public string Position
        {
            get { return _Position; }
            set
            {
                if(_Position!=value){
                    _Position=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Position");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            ClientUser item = new ClientUser(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(ClientUser clientUser){
			
			if (clientUser != null)
			{
				try 
				{
					
					this.Id = clientUser.Id;
					
										
					this.ClientId = clientUser.ClientId;
					
										
					this.aspnet_UserId = clientUser.aspnet_UserId;
					
										
					this.Position = clientUser.Position;
					
										
					this.CreatedOn = clientUser.CreatedOn;
					
										
					this.CreatedBy = clientUser.CreatedBy;
					
										
					this.ModifiedOn = clientUser.ModifiedOn;
					
										
					this.ModifiedBy = clientUser.ModifiedBy;
					
										
					this.IsDeleted = clientUser.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public ClientUser(ClientUser clientUser):this() {

			Load(clientUser);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<ClientUser, bool>> expression) {
            var repo = GetRepo();
            
            
            List<ClientUser> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<ClientUser, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the MessageHistory table in the RingCast Database.
    /// </summary>
    public partial class MessageHistory: BusinessObject<MessageHistory>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<MessageHistory>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<MessageHistory> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<MessageHistory>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<MessageHistory> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(MessageHistory item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                MessageHistory item=new MessageHistory();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<MessageHistory> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public MessageHistory(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                MessageHistory.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<MessageHistory>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public MessageHistory(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public MessageHistory(Expression<Func<MessageHistory, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<MessageHistory> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<MessageHistory> _repo;
            
            if(db.TestMode){
                MessageHistory.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<MessageHistory>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<MessageHistory> GetRepo(){
            return GetRepo("","");
        }
        
        public static MessageHistory SingleOrDefault(Expression<Func<MessageHistory, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            MessageHistory single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static MessageHistory SingleOrDefault(Expression<Func<MessageHistory, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            MessageHistory single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<MessageHistory, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<MessageHistory, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<MessageHistory> Find(Expression<Func<MessageHistory, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<MessageHistory> Find(Expression<Func<MessageHistory, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<MessageHistory> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<MessageHistory> All() {
            return GetRepo().GetAll();
        }

		public static List<MessageHistory> FetchAll(string connectionString, string providerName) 
		{
            IRepository<MessageHistory> repo = RingCast.MessageHistory.GetRepo(connectionString,providerName);
			CachedDataLoader<MessageHistory>.DataRequest dataRequest 
			= new CachedDataLoader<MessageHistory>.DataRequest("RingCast", connectionString, "MessageHistory", repo);

			return CachedDataLoader<MessageHistory>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<MessageHistory> FetchAll(Expression<Func<MessageHistory, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<MessageHistory> repo = RingCast.MessageHistory.GetRepo();
			CachedDataLoader<MessageHistory>.DataRequest dataRequest 
			= new CachedDataLoader<MessageHistory>.DataRequest("RingCast", db.DataProvider.ConnectionString, "MessageHistory", repo, expression);

			return CachedDataLoader<MessageHistory>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<MessageHistory> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<MessageHistory> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<MessageHistory> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<MessageHistory> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<MessageHistory> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Details.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(MessageHistory)){
                MessageHistory compare=(MessageHistory)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Details.ToString();
        }

        public string DescriptorColumn() {
            return "Details";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Details";
        }
        
        #region ' Foreign Keys '
		private List<Message> _Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.Id == MessageId;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<MessageStatus> _MessageStatuses
        {
            get
            {            
				IRepository<_MessageStatus> repo = RingCast._MessageStatus.GetRepo();
				Expression<Func<_MessageStatus, bool>> expression = x => x.Id == MessageStatusId;
				CachedDataLoader<_MessageStatus>.DataRequest dataRequest 
				= new CachedDataLoader<_MessageStatus>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "MessageStatuses", repo, expression);

				List<MessageStatus> list = new List<MessageStatus>();
				
				foreach (_MessageStatus item in CachedDataLoader<_MessageStatus>.GetCachedData(dataRequest).ToList())
				{
					list.Add((MessageStatus)item.Id);
				}
				
				return list;
            }
        }
		
		
		public Message Message
		{
			get
			{
				return _Messages.SingleOrDefault(x => x.Id == _MessageId);
			}								
			set
			{
				MessageId = value.Id;
			}
		}

		public MessageStatus MessageStatus
		{
			get
			{
				return (MessageStatus)MessageStatusId;
			}								
			set
			{
				MessageStatusId = (int)value;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MessageId;
		 [XmlIgnore] 
        public int MessageId
        {
            get { return _MessageId; }
            set
            {
                if(_MessageId!=value){
                    _MessageId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MessageId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MessageStatusId;
		 [XmlIgnore] 
        public int MessageStatusId
        {
            get { return _MessageStatusId; }
            set
            {
                if(_MessageStatusId!=value){
                    _MessageStatusId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MessageStatusId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Details;
		  
        public string Details
        {
            get { return _Details; }
            set
            {
                if(_Details!=value){
                    _Details=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Details");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            MessageHistory item = new MessageHistory(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(MessageHistory messageHistory){
			
			if (messageHistory != null)
			{
				try 
				{
					
					this.Id = messageHistory.Id;
					
										
					this.MessageId = messageHistory.MessageId;
					
										
					this.MessageStatusId = messageHistory.MessageStatusId;
					
										
					this.Details = messageHistory.Details;
					
										
					this.CreatedOn = messageHistory.CreatedOn;
					
										
					this.CreatedBy = messageHistory.CreatedBy;
					
										
					this.ModifiedOn = messageHistory.ModifiedOn;
					
										
					this.ModifiedBy = messageHistory.ModifiedBy;
					
										
					this.IsDeleted = messageHistory.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public MessageHistory(MessageHistory messageHistory):this() {

			Load(messageHistory);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<MessageHistory, bool>> expression) {
            var repo = GetRepo();
            
            
            List<MessageHistory> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<MessageHistory, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the ClientStatuses table in the RingCast Database.
    /// </summary>
    public partial class _ClientStatus: BusinessObject<_ClientStatus>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<_ClientStatus>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<_ClientStatus> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<_ClientStatus>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<_ClientStatus> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(_ClientStatus item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                _ClientStatus item=new _ClientStatus();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<_ClientStatus> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public _ClientStatus(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                _ClientStatus.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_ClientStatus>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public _ClientStatus(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public _ClientStatus(Expression<Func<_ClientStatus, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<_ClientStatus> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<_ClientStatus> _repo;
            
            if(db.TestMode){
                _ClientStatus.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_ClientStatus>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<_ClientStatus> GetRepo(){
            return GetRepo("","");
        }
        
        public static _ClientStatus SingleOrDefault(Expression<Func<_ClientStatus, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            _ClientStatus single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static _ClientStatus SingleOrDefault(Expression<Func<_ClientStatus, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            _ClientStatus single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<_ClientStatus, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<_ClientStatus, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<_ClientStatus> Find(Expression<Func<_ClientStatus, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<_ClientStatus> Find(Expression<Func<_ClientStatus, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<_ClientStatus> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<_ClientStatus> All() {
            return GetRepo().GetAll();
        }

		public static List<_ClientStatus> FetchAll(string connectionString, string providerName) 
		{
            IRepository<_ClientStatus> repo = RingCast._ClientStatus.GetRepo(connectionString,providerName);
			CachedDataLoader<_ClientStatus>.DataRequest dataRequest 
			= new CachedDataLoader<_ClientStatus>.DataRequest("RingCast", connectionString, "ClientStatuses", repo);

			return CachedDataLoader<_ClientStatus>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<_ClientStatus> FetchAll(Expression<Func<_ClientStatus, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<_ClientStatus> repo = RingCast._ClientStatus.GetRepo();
			CachedDataLoader<_ClientStatus>.DataRequest dataRequest 
			= new CachedDataLoader<_ClientStatus>.DataRequest("RingCast", db.DataProvider.ConnectionString, "ClientStatuses", repo, expression);

			return CachedDataLoader<_ClientStatus>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<_ClientStatus> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<_ClientStatus> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<_ClientStatus> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<_ClientStatus> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<_ClientStatus> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(_ClientStatus)){
                _ClientStatus compare=(_ClientStatus)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<Client> _Clients;
		public List<Client> Clients
        {
            get
            {            
				IRepository<Client> repo = RingCast.Client.GetRepo();
				Expression<Func<Client, bool>> expression = x => x.ClientStatusId == Id;
				CachedDataLoader<Client>.DataRequest dataRequest 
				= new CachedDataLoader<Client>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Clients", repo, expression);

				return CachedDataLoader<Client>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Clients = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Clients != null && Clients.Count > 0)
				Clients.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Clients != null && Clients.Count > 0)
				Clients.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            _ClientStatus item = new _ClientStatus(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(_ClientStatus _ClientStatus){
			
			if (_ClientStatus != null)
			{
				try 
				{
					
					this.Id = _ClientStatus.Id;
					
										
					this.Name = _ClientStatus.Name;
					
										
					this.CreatedOn = _ClientStatus.CreatedOn;
					
										
					this.CreatedBy = _ClientStatus.CreatedBy;
					
										
					this.ModifiedOn = _ClientStatus.ModifiedOn;
					
										
					this.ModifiedBy = _ClientStatus.ModifiedBy;
					
										
					this.IsDeleted = _ClientStatus.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public _ClientStatus(_ClientStatus _ClientStatus):this() {

			Load(_ClientStatus);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<_ClientStatus, bool>> expression) {
            var repo = GetRepo();
            
            
            List<_ClientStatus> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<_ClientStatus, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the OutboundBatch table in the RingCast Database.
    /// </summary>
    public partial class OutboundBatch: BusinessObject<OutboundBatch>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<OutboundBatch>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<OutboundBatch> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<OutboundBatch>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<OutboundBatch> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(OutboundBatch item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                OutboundBatch item=new OutboundBatch();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<OutboundBatch> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public OutboundBatch(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                OutboundBatch.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<OutboundBatch>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public OutboundBatch(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public OutboundBatch(Expression<Func<OutboundBatch, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<OutboundBatch> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<OutboundBatch> _repo;
            
            if(db.TestMode){
                OutboundBatch.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<OutboundBatch>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<OutboundBatch> GetRepo(){
            return GetRepo("","");
        }
        
        public static OutboundBatch SingleOrDefault(Expression<Func<OutboundBatch, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            OutboundBatch single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static OutboundBatch SingleOrDefault(Expression<Func<OutboundBatch, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            OutboundBatch single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<OutboundBatch, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<OutboundBatch, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<OutboundBatch> Find(Expression<Func<OutboundBatch, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<OutboundBatch> Find(Expression<Func<OutboundBatch, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<OutboundBatch> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<OutboundBatch> All() {
            return GetRepo().GetAll();
        }

		public static List<OutboundBatch> FetchAll(string connectionString, string providerName) 
		{
            IRepository<OutboundBatch> repo = RingCast.OutboundBatch.GetRepo(connectionString,providerName);
			CachedDataLoader<OutboundBatch>.DataRequest dataRequest 
			= new CachedDataLoader<OutboundBatch>.DataRequest("RingCast", connectionString, "OutboundBatch", repo);

			return CachedDataLoader<OutboundBatch>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<OutboundBatch> FetchAll(Expression<Func<OutboundBatch, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<OutboundBatch> repo = RingCast.OutboundBatch.GetRepo();
			CachedDataLoader<OutboundBatch>.DataRequest dataRequest 
			= new CachedDataLoader<OutboundBatch>.DataRequest("RingCast", db.DataProvider.ConnectionString, "OutboundBatch", repo, expression);

			return CachedDataLoader<OutboundBatch>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<OutboundBatch> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<OutboundBatch> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<OutboundBatch> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<OutboundBatch> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<OutboundBatch> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(OutboundBatch)){
                OutboundBatch compare=(OutboundBatch)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<OutboundBatchMessage> _Messages;
		public List<OutboundBatchMessage> Messages
        {
            get
            {            
				IRepository<OutboundBatchMessage> repo = RingCast.OutboundBatchMessage.GetRepo();
				Expression<Func<OutboundBatchMessage, bool>> expression = x => x.OutboundBatchId == Id;
				CachedDataLoader<OutboundBatchMessage>.DataRequest dataRequest 
				= new CachedDataLoader<OutboundBatchMessage>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "OutboundBatchMessages", repo, expression);

				return CachedDataLoader<OutboundBatchMessage>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Messages = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Messages != null && Messages.Count > 0)
				Messages.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            OutboundBatch item = new OutboundBatch(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(OutboundBatch outboundBatch){
			
			if (outboundBatch != null)
			{
				try 
				{
					
					this.Id = outboundBatch.Id;
					
										
					this.Name = outboundBatch.Name;
					
										
					this.CreatedOn = outboundBatch.CreatedOn;
					
										
					this.CreatedBy = outboundBatch.CreatedBy;
					
										
					this.ModifiedOn = outboundBatch.ModifiedOn;
					
										
					this.ModifiedBy = outboundBatch.ModifiedBy;
					
										
					this.IsDeleted = outboundBatch.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public OutboundBatch(OutboundBatch outboundBatch):this() {

			Load(outboundBatch);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<OutboundBatch, bool>> expression) {
            var repo = GetRepo();
            
            
            List<OutboundBatch> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<OutboundBatch, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the Clients table in the RingCast Database.
    /// </summary>
    public partial class Client: BusinessObject<Client>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<Client>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<Client> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<Client>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<Client> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(Client item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                Client item=new Client();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<Client> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public Client(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                Client.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Client>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public Client(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public Client(Expression<Func<Client, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<Client> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<Client> _repo;
            
            if(db.TestMode){
                Client.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<Client>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<Client> GetRepo(){
            return GetRepo("","");
        }
        
        public static Client SingleOrDefault(Expression<Func<Client, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            Client single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static Client SingleOrDefault(Expression<Func<Client, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            Client single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<Client, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<Client, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<Client> Find(Expression<Func<Client, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<Client> Find(Expression<Func<Client, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<Client> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<Client> All() {
            return GetRepo().GetAll();
        }

		public static List<Client> FetchAll(string connectionString, string providerName) 
		{
            IRepository<Client> repo = RingCast.Client.GetRepo(connectionString,providerName);
			CachedDataLoader<Client>.DataRequest dataRequest 
			= new CachedDataLoader<Client>.DataRequest("RingCast", connectionString, "Clients", repo);

			return CachedDataLoader<Client>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<Client> FetchAll(Expression<Func<Client, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<Client> repo = RingCast.Client.GetRepo();
			CachedDataLoader<Client>.DataRequest dataRequest 
			= new CachedDataLoader<Client>.DataRequest("RingCast", db.DataProvider.ConnectionString, "Clients", repo, expression);

			return CachedDataLoader<Client>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<Client> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<Client> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<Client> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<Client> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<Client> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(Client)){
                Client compare=(Client)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		private List<ClientStatus> _ClientStatuses
        {
            get
            {            
				IRepository<_ClientStatus> repo = RingCast._ClientStatus.GetRepo();
				Expression<Func<_ClientStatus, bool>> expression = x => x.Id == ClientStatusId;
				CachedDataLoader<_ClientStatus>.DataRequest dataRequest 
				= new CachedDataLoader<_ClientStatus>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "ClientStatuses", repo, expression);

				List<ClientStatus> list = new List<ClientStatus>();
				
				foreach (_ClientStatus item in CachedDataLoader<_ClientStatus>.GetCachedData(dataRequest).ToList())
				{
					list.Add((ClientStatus)item.Id);
				}
				
				return list;
            }
        }
		
		
		
		private List<Campaign> _Campaigns;
		public List<Campaign> Campaigns
        {
            get
            {            
				IRepository<Campaign> repo = RingCast.Campaign.GetRepo();
				Expression<Func<Campaign, bool>> expression = x => x.ClientId == Id;
				CachedDataLoader<Campaign>.DataRequest dataRequest 
				= new CachedDataLoader<Campaign>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Campaigns", repo, expression);

				return CachedDataLoader<Campaign>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Campaigns = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<ClientGatewayCredential> _GatewayCredentials;
		public List<ClientGatewayCredential> GatewayCredentials
        {
            get
            {            
				IRepository<ClientGatewayCredential> repo = RingCast.ClientGatewayCredential.GetRepo();
				Expression<Func<ClientGatewayCredential, bool>> expression = x => x.ClientId == Id;
				CachedDataLoader<ClientGatewayCredential>.DataRequest dataRequest 
				= new CachedDataLoader<ClientGatewayCredential>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "ClientGatewayCredentials", repo, expression);

				return CachedDataLoader<ClientGatewayCredential>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _GatewayCredentials = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<ClientShellCredential> _ShellCredentials;
		public List<ClientShellCredential> ShellCredentials
        {
            get
            {            
				IRepository<ClientShellCredential> repo = RingCast.ClientShellCredential.GetRepo();
				Expression<Func<ClientShellCredential, bool>> expression = x => x.ClientId == Id;
				CachedDataLoader<ClientShellCredential>.DataRequest dataRequest 
				= new CachedDataLoader<ClientShellCredential>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "ClientShellCredentials", repo, expression);

				return CachedDataLoader<ClientShellCredential>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _ShellCredentials = value;
               
               OnChanged();
            }
        }
		
		
		
		private List<ClientUser> _Users;
		public List<ClientUser> Users
        {
            get
            {            
				IRepository<ClientUser> repo = RingCast.ClientUser.GetRepo();
				Expression<Func<ClientUser, bool>> expression = x => x.ClientId == Id;
				CachedDataLoader<ClientUser>.DataRequest dataRequest 
				= new CachedDataLoader<ClientUser>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "ClientUsers", repo, expression);

				return CachedDataLoader<ClientUser>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Users = value;
               
               OnChanged();
            }
        }
		
		
		public ClientStatus Status
		{
			get
			{
				return (ClientStatus)ClientStatusId;
			}								
			set
			{
				ClientStatusId = (int)value;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Login;
		  
        public string Login
        {
            get { return _Login; }
            set
            {
                if(_Login!=value){
                    _Login=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Login");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Password;
		  
        public string Password
        {
            get { return _Password; }
            set
            {
                if(_Password!=value){
                    _Password=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Password");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _ClientStatusId;
		  
        public int ClientStatusId
        {
            get { return _ClientStatusId; }
            set
            {
                if(_ClientStatusId!=value){
                    _ClientStatusId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ClientStatusId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Campaigns != null && Campaigns.Count > 0)
				Campaigns.ForEach(x => x.Save(provider));	
				
			
			if (GatewayCredentials != null && GatewayCredentials.Count > 0)
				GatewayCredentials.ForEach(x => x.Save(provider));	
				
			
			if (ShellCredentials != null && ShellCredentials.Count > 0)
				ShellCredentials.ForEach(x => x.Save(provider));	
				
			
			if (Users != null && Users.Count > 0)
				Users.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Campaigns != null && Campaigns.Count > 0)
				Campaigns.ForEach(x => x.Save(username, provider));
				
			
			if (GatewayCredentials != null && GatewayCredentials.Count > 0)
				GatewayCredentials.ForEach(x => x.Save(username, provider));
				
			
			if (ShellCredentials != null && ShellCredentials.Count > 0)
				ShellCredentials.ForEach(x => x.Save(username, provider));
				
			
			if (Users != null && Users.Count > 0)
				Users.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            Client item = new Client(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(Client client){
			
			if (client != null)
			{
				try 
				{
					
					this.Id = client.Id;
					
										
					this.Name = client.Name;
					
										
					this.Login = client.Login;
					
										
					this.Password = client.Password;
					
										
					this.ClientStatusId = client.ClientStatusId;
					
										
					this.CreatedOn = client.CreatedOn;
					
										
					this.CreatedBy = client.CreatedBy;
					
										
					this.ModifiedOn = client.ModifiedOn;
					
										
					this.ModifiedBy = client.ModifiedBy;
					
										
					this.IsDeleted = client.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public Client(Client client):this() {

			Load(client);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<Client, bool>> expression) {
            var repo = GetRepo();
            
            
            List<Client> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<Client, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the PipeCampaignKeywords table in the RingCast Database.
    /// </summary>
    public partial class PipeCampaignKeyword: BusinessObject<PipeCampaignKeyword>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<PipeCampaignKeyword>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<PipeCampaignKeyword> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<PipeCampaignKeyword>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<PipeCampaignKeyword> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(PipeCampaignKeyword item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                PipeCampaignKeyword item=new PipeCampaignKeyword();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<PipeCampaignKeyword> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public PipeCampaignKeyword(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                PipeCampaignKeyword.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<PipeCampaignKeyword>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public PipeCampaignKeyword(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public PipeCampaignKeyword(Expression<Func<PipeCampaignKeyword, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<PipeCampaignKeyword> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<PipeCampaignKeyword> _repo;
            
            if(db.TestMode){
                PipeCampaignKeyword.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<PipeCampaignKeyword>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<PipeCampaignKeyword> GetRepo(){
            return GetRepo("","");
        }
        
        public static PipeCampaignKeyword SingleOrDefault(Expression<Func<PipeCampaignKeyword, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            PipeCampaignKeyword single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static PipeCampaignKeyword SingleOrDefault(Expression<Func<PipeCampaignKeyword, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            PipeCampaignKeyword single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<PipeCampaignKeyword, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<PipeCampaignKeyword, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<PipeCampaignKeyword> Find(Expression<Func<PipeCampaignKeyword, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<PipeCampaignKeyword> Find(Expression<Func<PipeCampaignKeyword, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<PipeCampaignKeyword> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<PipeCampaignKeyword> All() {
            return GetRepo().GetAll();
        }

		public static List<PipeCampaignKeyword> FetchAll(string connectionString, string providerName) 
		{
            IRepository<PipeCampaignKeyword> repo = RingCast.PipeCampaignKeyword.GetRepo(connectionString,providerName);
			CachedDataLoader<PipeCampaignKeyword>.DataRequest dataRequest 
			= new CachedDataLoader<PipeCampaignKeyword>.DataRequest("RingCast", connectionString, "PipeCampaignKeywords", repo);

			return CachedDataLoader<PipeCampaignKeyword>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<PipeCampaignKeyword> FetchAll(Expression<Func<PipeCampaignKeyword, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<PipeCampaignKeyword> repo = RingCast.PipeCampaignKeyword.GetRepo();
			CachedDataLoader<PipeCampaignKeyword>.DataRequest dataRequest 
			= new CachedDataLoader<PipeCampaignKeyword>.DataRequest("RingCast", db.DataProvider.ConnectionString, "PipeCampaignKeywords", repo, expression);

			return CachedDataLoader<PipeCampaignKeyword>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<PipeCampaignKeyword> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<PipeCampaignKeyword> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<PipeCampaignKeyword> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<PipeCampaignKeyword> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<PipeCampaignKeyword> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Keyword.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(PipeCampaignKeyword)){
                PipeCampaignKeyword compare=(PipeCampaignKeyword)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Keyword.ToString();
        }

        public string DescriptorColumn() {
            return "Keyword";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Keyword";
        }
        
        #region ' Foreign Keys '
		private List<Campaign> _Campaigns
        {
            get
            {            
				IRepository<Campaign> repo = RingCast.Campaign.GetRepo();
				Expression<Func<Campaign, bool>> expression = x => x.Id == CampaignId;
				CachedDataLoader<Campaign>.DataRequest dataRequest 
				= new CachedDataLoader<Campaign>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Campaigns", repo, expression);

				return CachedDataLoader<Campaign>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<Pipe> _Pipes
        {
            get
            {            
				IRepository<Pipe> repo = RingCast.Pipe.GetRepo();
				Expression<Func<Pipe, bool>> expression = x => x.Id == PipeId;
				CachedDataLoader<Pipe>.DataRequest dataRequest 
				= new CachedDataLoader<Pipe>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Pipes", repo, expression);

				return CachedDataLoader<Pipe>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Campaign Campaign
		{
			get
			{
				return _Campaigns.SingleOrDefault(x => x.Id == _CampaignId);
			}								
			set
			{
				CampaignId = value.Id;
			}
		}

		public Pipe Pipe
		{
			get
			{
				return _Pipes.SingleOrDefault(x => x.Id == _PipeId);
			}								
			set
			{
				PipeId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _PipeId;
		 [XmlIgnore] 
        public int PipeId
        {
            get { return _PipeId; }
            set
            {
                if(_PipeId!=value){
                    _PipeId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="PipeId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _CampaignId;
		 [XmlIgnore] 
        public int CampaignId
        {
            get { return _CampaignId; }
            set
            {
                if(_CampaignId!=value){
                    _CampaignId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CampaignId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Keyword;
		  
        public string Keyword
        {
            get { return _Keyword; }
            set
            {
                if(_Keyword!=value){
                    _Keyword=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Keyword");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            PipeCampaignKeyword item = new PipeCampaignKeyword(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(PipeCampaignKeyword pipeCampaignKeyword){
			
			if (pipeCampaignKeyword != null)
			{
				try 
				{
					
					this.Id = pipeCampaignKeyword.Id;
					
										
					this.PipeId = pipeCampaignKeyword.PipeId;
					
										
					this.CampaignId = pipeCampaignKeyword.CampaignId;
					
										
					this.Keyword = pipeCampaignKeyword.Keyword;
					
										
					this.CreatedOn = pipeCampaignKeyword.CreatedOn;
					
										
					this.CreatedBy = pipeCampaignKeyword.CreatedBy;
					
										
					this.ModifiedOn = pipeCampaignKeyword.ModifiedOn;
					
										
					this.ModifiedBy = pipeCampaignKeyword.ModifiedBy;
					
										
					this.IsDeleted = pipeCampaignKeyword.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public PipeCampaignKeyword(PipeCampaignKeyword pipeCampaignKeyword):this() {

			Load(pipeCampaignKeyword);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<PipeCampaignKeyword, bool>> expression) {
            var repo = GetRepo();
            
            
            List<PipeCampaignKeyword> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<PipeCampaignKeyword, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the BillingTypes table in the RingCast Database.
    /// </summary>
    public partial class _BillingType: BusinessObject<_BillingType>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<_BillingType>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<_BillingType> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<_BillingType>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<_BillingType> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(_BillingType item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                _BillingType item=new _BillingType();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<_BillingType> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public _BillingType(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                _BillingType.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_BillingType>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public _BillingType(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public _BillingType(Expression<Func<_BillingType, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<_BillingType> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<_BillingType> _repo;
            
            if(db.TestMode){
                _BillingType.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<_BillingType>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<_BillingType> GetRepo(){
            return GetRepo("","");
        }
        
        public static _BillingType SingleOrDefault(Expression<Func<_BillingType, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            _BillingType single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static _BillingType SingleOrDefault(Expression<Func<_BillingType, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            _BillingType single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<_BillingType, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<_BillingType, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<_BillingType> Find(Expression<Func<_BillingType, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<_BillingType> Find(Expression<Func<_BillingType, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<_BillingType> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<_BillingType> All() {
            return GetRepo().GetAll();
        }

		public static List<_BillingType> FetchAll(string connectionString, string providerName) 
		{
            IRepository<_BillingType> repo = RingCast._BillingType.GetRepo(connectionString,providerName);
			CachedDataLoader<_BillingType>.DataRequest dataRequest 
			= new CachedDataLoader<_BillingType>.DataRequest("RingCast", connectionString, "BillingTypes", repo);

			return CachedDataLoader<_BillingType>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<_BillingType> FetchAll(Expression<Func<_BillingType, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<_BillingType> repo = RingCast._BillingType.GetRepo();
			CachedDataLoader<_BillingType>.DataRequest dataRequest 
			= new CachedDataLoader<_BillingType>.DataRequest("RingCast", db.DataProvider.ConnectionString, "BillingTypes", repo, expression);

			return CachedDataLoader<_BillingType>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<_BillingType> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<_BillingType> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<_BillingType> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<_BillingType> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<_BillingType> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Name.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(_BillingType)){
                _BillingType compare=(_BillingType)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Name.ToString();
        }

        public string DescriptorColumn() {
            return "Name";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Name";
        }
        
        #region ' Foreign Keys '
		
		private List<Pipe> _Pipes;
		public List<Pipe> Pipes
        {
            get
            {            
				IRepository<Pipe> repo = RingCast.Pipe.GetRepo();
				Expression<Func<Pipe, bool>> expression = x => x.BillingTypeId == Id;
				CachedDataLoader<Pipe>.DataRequest dataRequest 
				= new CachedDataLoader<Pipe>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Pipes", repo, expression);

				return CachedDataLoader<Pipe>.GetCachedData(dataRequest).ToList();
            }
            set
            {
               _Pipes = value;
               
               OnChanged();
            }
        }
		
		
        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Name;
		  
        public string Name
        {
            get { return _Name; }
            set
            {
                if(_Name!=value){
                    _Name=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Name");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
            saveForeign(provider);
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
            saveForeign(username, provider);
  
            
        }
        

        
        private void saveForeign(IDataProvider provider)
		{
			
			if (Pipes != null && Pipes.Count > 0)
				Pipes.ForEach(x => x.Save(provider));	
				
		}

		private void saveForeign(string username, IDataProvider provider)
		{
			
			if (Pipes != null && Pipes.Count > 0)
				Pipes.ForEach(x => x.Save(username, provider));
				
		} 		
  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            _BillingType item = new _BillingType(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(_BillingType _BillingType){
			
			if (_BillingType != null)
			{
				try 
				{
					
					this.Id = _BillingType.Id;
					
										
					this.Name = _BillingType.Name;
					
										
					this.CreatedOn = _BillingType.CreatedOn;
					
										
					this.CreatedBy = _BillingType.CreatedBy;
					
										
					this.ModifiedOn = _BillingType.ModifiedOn;
					
										
					this.ModifiedBy = _BillingType.ModifiedBy;
					
										
					this.IsDeleted = _BillingType.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public _BillingType(_BillingType _BillingType):this() {

			Load(_BillingType);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<_BillingType, bool>> expression) {
            var repo = GetRepo();
            
            
            List<_BillingType> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<_BillingType, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the CampaignIdentifierPool table in the RingCast Database.
    /// </summary>
    public partial class CampaignIdentifierPool: BusinessObject<CampaignIdentifierPool>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<CampaignIdentifierPool>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<CampaignIdentifierPool> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<CampaignIdentifierPool>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<CampaignIdentifierPool> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(CampaignIdentifierPool item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                CampaignIdentifierPool item=new CampaignIdentifierPool();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<CampaignIdentifierPool> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public CampaignIdentifierPool(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                CampaignIdentifierPool.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<CampaignIdentifierPool>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public CampaignIdentifierPool(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public CampaignIdentifierPool(Expression<Func<CampaignIdentifierPool, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<CampaignIdentifierPool> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<CampaignIdentifierPool> _repo;
            
            if(db.TestMode){
                CampaignIdentifierPool.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<CampaignIdentifierPool>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<CampaignIdentifierPool> GetRepo(){
            return GetRepo("","");
        }
        
        public static CampaignIdentifierPool SingleOrDefault(Expression<Func<CampaignIdentifierPool, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            CampaignIdentifierPool single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static CampaignIdentifierPool SingleOrDefault(Expression<Func<CampaignIdentifierPool, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            CampaignIdentifierPool single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<CampaignIdentifierPool, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<CampaignIdentifierPool, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<CampaignIdentifierPool> Find(Expression<Func<CampaignIdentifierPool, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<CampaignIdentifierPool> Find(Expression<Func<CampaignIdentifierPool, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<CampaignIdentifierPool> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<CampaignIdentifierPool> All() {
            return GetRepo().GetAll();
        }

		public static List<CampaignIdentifierPool> FetchAll(string connectionString, string providerName) 
		{
            IRepository<CampaignIdentifierPool> repo = RingCast.CampaignIdentifierPool.GetRepo(connectionString,providerName);
			CachedDataLoader<CampaignIdentifierPool>.DataRequest dataRequest 
			= new CachedDataLoader<CampaignIdentifierPool>.DataRequest("RingCast", connectionString, "CampaignIdentifierPool", repo);

			return CachedDataLoader<CampaignIdentifierPool>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<CampaignIdentifierPool> FetchAll(Expression<Func<CampaignIdentifierPool, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<CampaignIdentifierPool> repo = RingCast.CampaignIdentifierPool.GetRepo();
			CachedDataLoader<CampaignIdentifierPool>.DataRequest dataRequest 
			= new CachedDataLoader<CampaignIdentifierPool>.DataRequest("RingCast", db.DataProvider.ConnectionString, "CampaignIdentifierPool", repo, expression);

			return CachedDataLoader<CampaignIdentifierPool>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<CampaignIdentifierPool> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<CampaignIdentifierPool> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<CampaignIdentifierPool> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<CampaignIdentifierPool> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<CampaignIdentifierPool> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.Identifier.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(CampaignIdentifierPool)){
                CampaignIdentifierPool compare=(CampaignIdentifierPool)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.Identifier.ToString();
        }

        public string DescriptorColumn() {
            return "Identifier";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "Identifier";
        }
        
        #region ' Foreign Keys '
		private List<Campaign> _Campaigns
        {
            get
            {            
				IRepository<Campaign> repo = RingCast.Campaign.GetRepo();
				Expression<Func<Campaign, bool>> expression = x => x.Id == CampaignId;
				CachedDataLoader<Campaign>.DataRequest dataRequest 
				= new CachedDataLoader<Campaign>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Campaigns", repo, expression);

				return CachedDataLoader<Campaign>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Campaign Campaign
		{
			get
			{
				return _Campaigns.SingleOrDefault(x => x.Id == _CampaignId);
			}								
			set
			{
				CampaignId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _CampaignId;
		 [XmlIgnore] 
        public int CampaignId
        {
            get { return _CampaignId; }
            set
            {
                if(_CampaignId!=value){
                    _CampaignId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CampaignId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _Identifier;
		  
        public string Identifier
        {
            get { return _Identifier; }
            set
            {
                if(_Identifier!=value){
                    _Identifier=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Identifier");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            CampaignIdentifierPool item = new CampaignIdentifierPool(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(CampaignIdentifierPool campaignIdentifierPool){
			
			if (campaignIdentifierPool != null)
			{
				try 
				{
					
					this.Id = campaignIdentifierPool.Id;
					
										
					this.CampaignId = campaignIdentifierPool.CampaignId;
					
										
					this.Identifier = campaignIdentifierPool.Identifier;
					
										
					this.CreatedOn = campaignIdentifierPool.CreatedOn;
					
										
					this.CreatedBy = campaignIdentifierPool.CreatedBy;
					
										
					this.ModifiedOn = campaignIdentifierPool.ModifiedOn;
					
										
					this.ModifiedBy = campaignIdentifierPool.ModifiedBy;
					
										
					this.IsDeleted = campaignIdentifierPool.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public CampaignIdentifierPool(CampaignIdentifierPool campaignIdentifierPool):this() {

			Load(campaignIdentifierPool);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<CampaignIdentifierPool, bool>> expression) {
            var repo = GetRepo();
            
            
            List<CampaignIdentifierPool> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<CampaignIdentifierPool, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
 
			
    /// <summary>
    /// A class which represents the OutboundBatchMessages table in the RingCast Database.
    /// </summary>
    public partial class OutboundBatchMessage: BusinessObject<OutboundBatchMessage>, IActiveRecord
    {
		public static XmlQualifiedName ProvideSchema(XmlSchemaSet SchemaSet)
		{
			return XmlSerializer<OutboundBatchMessage>.ProvideSchema(SchemaSet, "http://ChangeThis");
		}		    
    
        #region Built-in testing
        static TestRepository<OutboundBatchMessage> _testRepo;
        

        
        static void SetTestRepo(){
            _testRepo = _testRepo ?? new TestRepository<OutboundBatchMessage>(new RingCast.RingCastDB());
        }
        public static void ResetTestRepo(){
            _testRepo = null;
            SetTestRepo();
        }
        public static void Setup(List<OutboundBatchMessage> testlist){
            SetTestRepo();
            _testRepo._items = testlist;
        }
        public static void Setup(OutboundBatchMessage item) {
            SetTestRepo();
            _testRepo._items.Add(item);
        }
        public static void Setup(int testItems) {
            SetTestRepo();
            for(int i=0;i<testItems;i++){
                OutboundBatchMessage item=new OutboundBatchMessage();
                _testRepo._items.Add(item);
            }
        }
        
        public bool TestMode = false;


        #endregion

        IRepository<OutboundBatchMessage> _repo;
        ITable tbl;
        bool _isNew;
        public bool IsNew(){
            return _isNew;
        }
        
        public void SetIsLoaded(bool isLoaded){
            _isLoaded=isLoaded;
            if(isLoaded)
                OnLoaded();
        }
        
        public void SetIsNew(bool isNew){
            _isNew=isNew;
        }
        bool _isLoaded;
        public bool IsLoaded(){
            return _isLoaded;
        }
                
        List<IColumn> _dirtyColumns;
        public bool IsDirty(){
            return _dirtyColumns.Count>0;
        }
        
        public List<IColumn> GetDirtyColumns (){
            return _dirtyColumns;
        }
        
        RingCast.RingCastDB _db;
        public OutboundBatchMessage(string connectionString, string providerName) {

            _db=new RingCast.RingCastDB(connectionString, providerName);
            Init();            
         }
        void Init(){
            TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
            _dirtyColumns=new List<IColumn>();
            if(TestMode){
                OutboundBatchMessage.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<OutboundBatchMessage>(_db);
            }
            tbl=_repo.GetTable();
            SetIsNew(true);
            OnCreated();       

        }
        
        public OutboundBatchMessage(){
             _db=new RingCast.RingCastDB();
            Init();            
        }
        
       
        partial void OnCreated();
            
        partial void OnLoaded();
        
        partial void OnSaved();
        
        partial void OnChanged();
        
 		protected internal IList<IColumn> Columns{
            get{
                return tbl.Columns;
            }
        }

        public OutboundBatchMessage(Expression<Func<OutboundBatchMessage, bool>> expression):this() {

            SetIsLoaded(_repo.Load(this,expression));
        }
        
        internal static IRepository<OutboundBatchMessage> GetRepo(string connectionString, string providerName){
            RingCast.RingCastDB db;
            if(String.IsNullOrEmpty(connectionString)){
                db=new RingCast.RingCastDB();
            }else{
                db=new RingCast.RingCastDB(connectionString, providerName);
            }
            IRepository<OutboundBatchMessage> _repo;
            
            if(db.TestMode){
                OutboundBatchMessage.SetTestRepo();
                _repo=_testRepo;
            }else{
                _repo = new SubSonicRepository<OutboundBatchMessage>(db);
            }
            return _repo;        
        }       
        
        internal static IRepository<OutboundBatchMessage> GetRepo(){
            return GetRepo("","");
        }
        
        public static OutboundBatchMessage SingleOrDefault(Expression<Func<OutboundBatchMessage, bool>> expression) {

            var repo = GetRepo();
            var results=repo.Find(expression);
            OutboundBatchMessage single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
                single.OnLoaded();
                single.SetIsLoaded(true);
                single.SetIsNew(false);
            }

            return single;
        }      
        
        public static OutboundBatchMessage SingleOrDefault(Expression<Func<OutboundBatchMessage, bool>> expression,string connectionString, string providerName) {
            var repo = GetRepo(connectionString,providerName);
            var results=repo.Find(expression);
            OutboundBatchMessage single=null;
            if(results.Count() > 0){
                single=results.ToList()[0];
            }

            return single;


        }
        
        
        public static bool Exists(Expression<Func<OutboundBatchMessage, bool>> expression,string connectionString, string providerName) {
           
            return All(connectionString,providerName).Any(expression);
        }        
        public static bool Exists(Expression<Func<OutboundBatchMessage, bool>> expression) {
           
            return All().Any(expression);
        }        

        public static IList<OutboundBatchMessage> Find(Expression<Func<OutboundBatchMessage, bool>> expression) {
            
            var repo = GetRepo();
            return repo.Find(expression).ToList();
        }
        
        public static IList<OutboundBatchMessage> Find(Expression<Func<OutboundBatchMessage, bool>> expression,string connectionString, string providerName) {

            var repo = GetRepo(connectionString,providerName);
            return repo.Find(expression).ToList();

        }

		public static IQueryable<OutboundBatchMessage> All(string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetAll();
        }
        public static IQueryable<OutboundBatchMessage> All() {
            return GetRepo().GetAll();
        }

		public static List<OutboundBatchMessage> FetchAll(string connectionString, string providerName) 
		{
            IRepository<OutboundBatchMessage> repo = RingCast.OutboundBatchMessage.GetRepo(connectionString,providerName);
			CachedDataLoader<OutboundBatchMessage>.DataRequest dataRequest 
			= new CachedDataLoader<OutboundBatchMessage>.DataRequest("RingCast", connectionString, "OutboundBatchMessages", repo);

			return CachedDataLoader<OutboundBatchMessage>.GetCachedData(dataRequest).ToList();
        }
		
		public static List<OutboundBatchMessage> FetchAll(Expression<Func<OutboundBatchMessage, bool>> expression) 
        {
			RingCastDB db = new RingCastDB();
        
            IRepository<OutboundBatchMessage> repo = RingCast.OutboundBatchMessage.GetRepo();
			CachedDataLoader<OutboundBatchMessage>.DataRequest dataRequest 
			= new CachedDataLoader<OutboundBatchMessage>.DataRequest("RingCast", db.DataProvider.ConnectionString, "OutboundBatchMessages", repo, expression);

			return CachedDataLoader<OutboundBatchMessage>.GetCachedData(dataRequest).ToList();
        }
        
        public static List<OutboundBatchMessage> FetchAll() 
        {
			return FetchAll(null);
        }

        public static PagedList<OutboundBatchMessage> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
        }
      
        public static PagedList<OutboundBatchMessage> GetPaged(string sortBy, int pageIndex, int pageSize) {
            return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
        }

        public static PagedList<OutboundBatchMessage> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
            return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
            
        }


        public static PagedList<OutboundBatchMessage> GetPaged(int pageIndex, int pageSize) {
            return GetRepo().GetPaged(pageIndex, pageSize);
            
        }

        public string KeyName()
        {
            return "Id";
        }

        public object KeyValue()
        {
            return this.Id;
        }
        
        public void SetKeyValue(object value) {
            if (value != null && value!=DBNull.Value) {
                var settable = value.ChangeTypeTo<int>();
                this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
            }
        }
        
        public override string ToString(){
            return this.CreatedBy.ToString();
        }

        public override bool Equals(object obj){
            if(obj.GetType()==typeof(OutboundBatchMessage)){
                OutboundBatchMessage compare=(OutboundBatchMessage)obj;
                return compare.KeyValue()==this.KeyValue();
            }else{
                return base.Equals(obj);
            }
        }

        
        public override int GetHashCode() {
            return this.Id;
        }
        
        public string DescriptorValue()
        {
            return this.CreatedBy.ToString();
        }

        public string DescriptorColumn() {
            return "CreatedBy";
        }
        public static string GetKeyColumn()
        {
            return "Id";
        }        
        public static string GetDescriptorColumn()
        {
            return "CreatedBy";
        }
        
        #region ' Foreign Keys '
		private List<Message> _Messages
        {
            get
            {            
				IRepository<Message> repo = RingCast.Message.GetRepo();
				Expression<Func<Message, bool>> expression = x => x.Id == MessageId;
				CachedDataLoader<Message>.DataRequest dataRequest 
				= new CachedDataLoader<Message>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "Messages", repo, expression);

				return CachedDataLoader<Message>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		private List<OutboundBatch> _OutboundBatches
        {
            get
            {            
				IRepository<OutboundBatch> repo = RingCast.OutboundBatch.GetRepo();
				Expression<Func<OutboundBatch, bool>> expression = x => x.Id == OutboundBatchId;
				CachedDataLoader<OutboundBatch>.DataRequest dataRequest 
				= new CachedDataLoader<OutboundBatch>.DataRequest("RingCast", _db.DataProvider.ConnectionString, "OutboundBatch", repo, expression);

				return CachedDataLoader<OutboundBatch>.GetCachedData(dataRequest).ToList();
            }
        }
		
		
		public Message Message
		{
			get
			{
				return _Messages.SingleOrDefault(x => x.Id == _MessageId);
			}								
			set
			{
				MessageId = value.Id;
			}
		}

		public OutboundBatch OutboundBatch
		{
			get
			{
				return _OutboundBatches.SingleOrDefault(x => x.Id == _OutboundBatchId);
			}								
			set
			{
				OutboundBatchId = value.Id;
			}
		}

        #endregion        


        int _Id;
		  
        public int Id
        {
            get { return _Id; }
            set
            {
                if(_Id!=value){
                    _Id=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _OutboundBatchId;
		 [XmlIgnore] 
        public int OutboundBatchId
        {
            get { return _OutboundBatchId; }
            set
            {
                if(_OutboundBatchId!=value){
                    _OutboundBatchId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="OutboundBatchId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        int _MessageId;
		 [XmlIgnore] 
        public int MessageId
        {
            get { return _MessageId; }
            set
            {
                if(_MessageId!=value){
                    _MessageId=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MessageId");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _CreatedOn;
		  
        public DateTime CreatedOn
        {
            get { return _CreatedOn; }
            set
            {
                if(_CreatedOn!=value){
                    _CreatedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _CreatedBy;
		  
        public string CreatedBy
        {
            get { return _CreatedBy; }
            set
            {
                if(_CreatedBy!=value){
                    _CreatedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="CreatedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        DateTime _ModifiedOn;
		  
        public DateTime ModifiedOn
        {
            get { return _ModifiedOn; }
            set
            {
                if(_ModifiedOn!=value){
                    _ModifiedOn=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedOn");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        string _ModifiedBy;
		  
        public string ModifiedBy
        {
            get { return _ModifiedBy; }
            set
            {
                if(_ModifiedBy!=value){
                    _ModifiedBy=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ModifiedBy");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }


        bool _IsDeleted;
		  
        public bool IsDeleted
        {
            get { return _IsDeleted; }
            set
            {
                if(_IsDeleted!=value){
                    _IsDeleted=value;
                    var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsDeleted");
                    if(col!=null){
                        if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
                            _dirtyColumns.Add(col);
                        }
                    }
                    OnChanged();
                }
            }
        }



        public DbCommand GetUpdateCommand() {
            if (!_dirtyColumns.Any(x => x.Name.ToLower() == "modifiedon")) {
               this.ModifiedOn=DateTime.Now;
            }            
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
            
        }
        public DbCommand GetInsertCommand() {
 
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
        }
        
        public DbCommand GetDeleteCommand() {
            if(TestMode)
                return _db.DataProvider.CreateCommand();
            else
                return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
        }
       
        
        public void Update(){
            Update(_db.DataProvider);
        }
        
        public void Update(IDataProvider provider){
        
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            
            if(this._dirtyColumns.Count>0)
                _repo.Update(this,provider);
            OnSaved();
       }
 
        public void Add(){
            Add(_db.DataProvider);
        }
        
                public void Update(string username){
            
            this.ModifiedBy=username;
            Update();

        }
        public void Update(string username, IDataProvider provider){

            this.ModifiedBy=username;
            Update(provider);
        }
        
       
        public void Add(IDataProvider provider){

            
            this.CreatedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.CreatedBy))
                this.CreatedBy=Environment.UserName;
            this.ModifiedOn=DateTime.Now;
            if(String.IsNullOrEmpty(this.ModifiedBy))
                this.ModifiedBy=Environment.UserName;
            
            var key=KeyValue();
            if(key==null){
                var newKey=_repo.Add(this,provider);
                this.SetKeyValue(newKey);
            }else{
                _repo.Add(this,provider);
            }
            SetIsNew(false);
            OnSaved();
        }
        
                public void Add(string username){
            
            this.CreatedBy=username;
            Add();

        }
        public void Add(string username, IDataProvider provider){

            this.CreatedBy=username;
            Add(provider);
        }
                
        
        public void Save() {
            Save(_db.DataProvider);
        }      
        public void Save(IDataProvider provider) {
            
           
            if (_isNew) {
                Add(provider);
                
            } else {
                Update(provider);
            }
            
          
        }

                public void Save(string username, IDataProvider provider) {
            
           
            if (_isNew) {
                                Add(username,provider);
                            } else {
                                Update(username,provider);
                
            }
            
  
            
        }
        

  
		
		public static void Delete(object key) {
            var repo = GetRepo();
            
            
            OutboundBatchMessage item = new OutboundBatchMessage(x => x.KeyValue() == key);
            item.IsDeleted = true;
            repo.Update(item);
            
        }
        
        protected void Load(OutboundBatchMessage outboundBatchMessage){
			
			if (outboundBatchMessage != null)
			{
				try 
				{
					
					this.Id = outboundBatchMessage.Id;
					
										
					this.OutboundBatchId = outboundBatchMessage.OutboundBatchId;
					
										
					this.MessageId = outboundBatchMessage.MessageId;
					
										
					this.CreatedOn = outboundBatchMessage.CreatedOn;
					
										
					this.CreatedBy = outboundBatchMessage.CreatedBy;
					
										
					this.ModifiedOn = outboundBatchMessage.ModifiedOn;
					
										
					this.ModifiedBy = outboundBatchMessage.ModifiedBy;
					
										
					this.IsDeleted = outboundBatchMessage.IsDeleted;
					
										SetIsNew(false);
					SetIsLoaded(true);
				} 
				catch 
				{
					SetIsLoaded(false);
					throw;
				}
            }
            else
            {
                SetIsLoaded(false);
            }
        }   
        
        public OutboundBatchMessage(OutboundBatchMessage outboundBatchMessage):this() {

			Load(outboundBatchMessage);
        }   
        

        public void Delete(IDataProvider provider) {
                         
             this.IsDeleted=true;
            _repo.Update(this,provider);
                
                    }


        public void Delete() {
            Delete(_db.DataProvider);
        }


        public static int Delete(Expression<Func<OutboundBatchMessage, bool>> expression) {
            var repo = GetRepo();
            
            
            List<OutboundBatchMessage> items=repo.GetAll().Where(expression).ToList();
            items.ForEach(x=>x.IsDeleted=true);
            return repo.Update(items);
            
        }

                
        public static int Destroy(Func<OutboundBatchMessage, bool> expression) {
            var repo = GetRepo();
            return repo.Delete(expression);
        }
        
        public static int Destroy(object key) {
            var repo = GetRepo();
            return repo.Delete(key);
        }
        
        public static int Destroy(object key, IDataProvider provider) {
        
            var repo = GetRepo();
            return repo.Delete(key,provider);
            
        }        
        
        public int Destroy() {
            return _repo.Delete(KeyValue());
        }        
        public int Destroy(IDataProvider provider) {
            return _repo.Delete(KeyValue(), provider);
        }         
        

        public void Load(IDataReader rdr) {
            Load(rdr, true);
        }
        public void Load(IDataReader rdr, bool closeReader) {
            if (rdr.Read()) {

                try {
                    rdr.Load(this);
                    SetIsNew(false);
                    SetIsLoaded(true);
                } catch {
                    SetIsLoaded(false);
                    throw;
                }
            }else{
                SetIsLoaded(false);
            }

            if (closeReader)
                rdr.Dispose();
        }
        

    } 
}
